Creating GPA calculator in C code - c

I just wrote this code and I cannot get it to work - not to mention output the desired results. I am supposed to create a program that will calculate the GPA of an unknown amount of students (which I have narrowed down to a max of 25) with an unknown amount of classes respectively (also narrowed those down to a max of 10 to make my life easier).
Can anyone see what mistakes I have made and possibly push me in the right direction? I appreciate anyone's time and advice :)
My Code:
// C Program - GPA calculator for x amount of students with x amount of classes
// Program developer: Diana Wright - Novembet 22nd, 2014
#include <stdio.h>
int main(void) {
// Declare variables
int grade[5], g, class_num[9], c;
char name[24], n;
float GPA=0.0, grade_point=0.0, result=0.0;
// Input student names implying amount of students
for(n=0; n<25; n++) {
scanf(" %s", &name[n]);
printf("Please enter student names: %s.", name[n]);
// Input number of classes
for(c=0; c<10; c++) {
scanf(" %d", &class_num[c]);
printf("Please enter amount of classes (max.10): %d", class_num[c]);
// Input grades
for(g=0; g<=class_num; g++) {
scanf(" %d", &grade[g]);
printf("Please enter students' grades: %d.", grade[g]);
}
// Conversion of grades
if (grade == "A"){
grade_point = 4.0;
}
if (grade == "B"){
grade_point = 3.0;
}
if (grade == "C")
{
grade_point =2.0;
}
if (grade == "D"){
grade_point = 1.0;
}
if (grade == "F"){
grade_point = 0.0;
}
// Formula to calculate GPA
result += grade_point[g];
GPA = result/class_num[c];
}
}
// Print user input and results in a table
printf(“\n Student name \t Grades \t GPA”);
for(n=0; n<25; n++) {
printf(“ %s \t %d \t %f”, name[n], grade[g], GPA);
}
return 0;
}
My initial input:
Diana 3 A A A Edward 4 B C B A Stuart 4 A F C D Bert 2 F F

// the following implements the needed data set,
// corrects several coding errors
// has (not yet run) compiling code
EDIT: following code obsolete, see new code further down
#include <stdio.h>
#include <string.h>
struct studentGrade
{
char name[24];
char grades[10];
int class_num;
float GPA;
};
int main(void)
{
// Declare variables
struct studentGrade studentGrades[25] = {{"",{'F','F','F','F','F','F','F','F','F','F'},0,0.0F}};
int c; // index into student grades[]
int n; // student number/loop counter
float grade_point=0.0f, result=0.0f;
// Input student names implying amount of students
for(n=0; n< (sizeof( studentGrades)/sizeof(struct studentGrade)); n++)
{
result = 0.0f; // initialize for each student
printf( "please enter student name:\n ");
scanf(" %s", (char*)(studentGrades[n].name) );
printf("Student Name is: %s.", studentGrades[n].name);
printf("please enter student class count:\n");
scanf(" %d", &studentGrades[n].class_num);
printf("Student Number of classes: %d", studentGrades[n].class_num);
// Input class grades
for(c=0; c< 10; c++)
{
printf("please enter grade for class: %d", c);
scanf(" %c", &(studentGrades[n].grades[c]));
printf("student grade for class: %d is %c\n", c, studentGrades[n].grades[c]);
// following makes wild assumption that grade entered
// is 'A'...'F'
// Conversion of grades
grade_point = 0.0f; // init for each class
switch( studentGrades[n].grades[c] )
{
case 'A':
grade_point = 4.0f;
break;
case 'B':
grade_point = 3.0f;
break;
case 'C':
grade_point = 2.0f;
break;
case 'D':
grade_point = 1.0f;
break;
case 'F':
grade_point = 0.0f;
break;
default:
printf( "invalid grade entered\n");
c--; // so will properly handle loop control, etc
break;
} // end switch
result += grade_point;
// Formula to calculate GPA
result += grade_point;
} // end for each grade
studentGrades[n].GPA = result/(float)c;
} // end for each student
// Print user input and results in a table
printf("\n Student name \tGPS\n\t\tgrades\n");
for(n=0; n< (sizeof(studentGrades) / sizeof( struct studentGrade)); n++)
{
if( 0 != strlen(studentGrades[n].name) )
{
printf( " %s \tGPS: %.2f\n",
studentGrades[n].name,
studentGrades[n].GPA);
for( c=0; c< studentGrades[n].class_num; c++)
{
printf("\tclass: %d\t%c:\n", c, studentGrades[n].grades[c] );
}
}
}
return 0;
}
EDIT: New code:
cleanly compiles
properly checks for errors
uses #define statements to eliminate 'magic' numbers
cleans up the logic error of always trying to input 10 grades
allows both upper case and lower case grade entry
uses meaningful variable names
incorporates appropriate horizontal spacing for readability
and now the new code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 25
#define MAX_NAME_LEN 23
#define MAX_GRADES 10
#define STR_VALUE(x) STR(x)
#define STR(x) #x
struct studentGrade
{
char name[ MAX_NAME_LEN+1 ];
char grades[ MAX_GRADES ];
int class_num;
float GPA;
};
int main(void)
{
// Declare variables
struct studentGrade studentGrades[ MAX_STUDENTS ] =
{
{"",
{'F','F','F','F','F','F','F','F','F','F'}
,0,
0.0F
}
};
float result = 0.0f;
// Input student names implying amount of students
for( size_t whichStudent=0;
whichStudent < (sizeof( studentGrades)/sizeof(struct studentGrade));
whichStudent++)
{
result = 0.0f; // initialize for each student
printf( "please enter student name:\n ");
if( scanf(" %" STR_VALUE(MAX_NAME_LEN) "s",
studentGrades[ whichStudent ].name ) != 1 )
{
fprintf( stderr, "scanf for student name failed");
exit( EXIT_FAILURE );
}
// implied else, scanf for student name successful
printf("Student Name is: %s.",
studentGrades[ whichStudent ].name);
printf("please enter student class count:\n");
if( scanf(" %d", &studentGrades[ whichStudent ].class_num) != 1 )
{
fprintf( stderr, "scanf for student class count failed\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf for student class count successful
printf("Student Number of classes: %d",
studentGrades[ whichStudent ].class_num);
// Input class grades
for( int whichClass=0;
whichClass < studentGrades[ whichStudent ].class_num;
whichClass++)
{
printf( "please enter grade for class: %d", whichClass );
if( scanf( " %c",
&(studentGrades[ whichStudent ].
grades[ whichClass ]) ) != 1)
{
fprintf( stderr,
"scanf for class grade %d failed\n",
whichClass );
exit( EXIT_FAILURE );
}
// implied else, scanf for class grade successful
printf( "student grade for class: %d is %d\n",
whichClass,
studentGrades[ whichStudent ].grades[ whichClass ] );
// following makes wild assumption that grade entered
// is 'A'...'F'
// Conversion of grades
float grade_point = 0.0f; // init for each class
switch( studentGrades[ whichStudent ].grades[ whichClass ] )
{
case 'A':
case 'a':
grade_point = 4.0f;
break;
case 'B':
case 'b':
grade_point = 3.0f;
break;
case 'C':
case 'c':
grade_point = 2.0f;
break;
case 'D':
case 'd':
grade_point = 1.0f;
break;
case 'F':
case 'f':
grade_point = 0.0f;
break;
default:
printf( "invalid grade entered\n");
whichClass--; // so will properly handle loop control, etc
break;
} // end switch
result += grade_point;
// Formula to calculate GPA
result += grade_point;
} // end for each grade
studentGrades[ whichStudent ].GPA =
result/(float)studentGrades[ whichStudent ].class_num;
} // end for each student
// Print user input and results in a table
printf( "\n Student name \tGPS\n\t\tgrades\n" );
for( size_t whichStudent=0;
whichStudent < (sizeof(studentGrades) / sizeof( struct studentGrade));
whichStudent++ )
{
if( 0 != strlen( studentGrades[ whichStudent ].name ) )
{
printf( " %s \tGPS: %.2f\n",
studentGrades[ whichStudent ].name,
studentGrades[ whichStudent ].GPA );
for( int whichClass=0;
whichClass < studentGrades[ whichStudent ].class_num;
whichClass++)
{
printf( "\tclass: %d\t%c:\n",
whichClass,
studentGrades[ whichStudent ].grades[ whichClass ] );
}
}
}
return 0;
}

Little rusty on this stuff, but I think there are a few strange things happening here that may not have been intended.
for(g=0; g<=class_num; g++)
Think we are looking for the inputted value that is stored at offset c, not the array.
for(c=0; c<10; c++)
I am not quite sure of the value of this loop. We should only have to get the number of classes once per student.
if (grade == "A")
Again, this didn't grab the right offset in the array. Do comparisons to char's need single quotes?
You are also going to have your print statements printing out a bunch... for example you might want to move this line outside the loop:
printf("Please enter students' grades: %d.", grade[g]);

So not to get on your case about anything whether this is or is not homework and to give credit to what laughingpine and Gopi have said already said...
There are some glaring errors in your code that will prevent you from compiling and running to have any effect. To start lets look at your declaration of variables:
// Declare variables
// You don't initialize any of your char or int non array and array variables.
int grade[5], g, class_num[9], c;
char name[24], n;
float GPA=0.0, grade_point=0.0, result=0.0; // You initialize your floating point variables.
When you initialize the compiler will designate an area of memory that these variables will reside in. If you don't then the compiler starts to make 'assumptions' on the variables you are using and will assign random memory locations to your variables. Next:
for (c = 0; c<10; c++) {
scanf(" %d", &class_num[c]); // You ask the user to enter one digit at a time for the class number
printf("Please enter amount of classes (max.10): %d", class_num[c]);
// Input grades
for (g = 0; g <= class_num; g++) // You try and make a comparison to a single variable int to an entire array which is not allowed.
{
scanf(" %d", &grade[g]);
printf("Please enter students' grades: %d.", grade[g]);
}
You cannot compare a single variable to an entire array, this line for (g = 0; g <= class_num; g++)will not compile. Another:
if (grade == "A"){
grade_point = 4.0;
}
You try to make a comparison from grade which is an int data type in your case to a string/character literal "A"which is not allowed...
result += grade_point[g]
Grade_point becomes an array here, when it was not defined this way before...
This looks like you rushed through the design process of your program. I recommend you sit down with a piece of paper and a pencil/pen and write out what it is you are trying to accomplish at each stage of asking the user for input. This will help in defining what variable data types you should be using in order to accomplish your tasks.

Related

Issues with do while loop

The code allows you to choose between star and delta resistive network conversions. There is also an exit option. I wanted to validate the values for R_a, R_b, R_c etc. however, I have run into some trouble with my do while loop. The lower limit is 1000 and the upper is 1000000.
I intend to have the program carry on if the input is within range and prompt for another input from the user if it is not. However, as of now, the program continues if the value is within range, but also continues after giving a warning when it is not - when I want it to loop back to the first input prompt.
Once correct, I will add the loop to all inputs.
If anyone is able to fix/find the issue, it would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
printf("\n\n\t\tDelta and Star Converter\n\n\n");
int choice, num, i;
unsigned long int fact;
while(1)
{
printf("1. Star \n");
printf("2. Delta\n");
printf("0. Exit\n\n\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:;
float R_a=0,R_b=0,R_c=0,R_ab,R_bc,R_ac;
printf("Please enter the value of the Star connected resistors:\n");
do {
printf("R_a = ");
scanf("%f",&R_a);
if (R_a > 1000000) {
printf("Please");
} else if (R_a < 1000) {
printf("Number to low\n");
}else {
}
}while(R_a = -0);
printf("R_b = ");
scanf("%f",&R_b);
printf("R_c = ");
scanf("%f",&R_c);
R_ab=R_a+R_b+(R_a*R_b)/R_c;
R_bc=R_b+R_c+(R_b*R_c)/R_a;
R_ac=R_a+R_c+(R_a*R_c)/R_b;
printf("the equivalent Delta values are: \n");
printf("R_ab = %.2f Ohms\n",R_ab);
printf("R_bc = %.2f Ohms\n",R_bc);
printf("R_ac = %.2f Ohms\n",R_ac);
break;
case 2:;
printf("Please enter the values of the Delta connected resistors:\n");
printf("R_ab = ");
scanf("%f",&R_ab);
printf("R_bc = ");
scanf("%f",&R_bc);
printf("R_ac = ");
scanf("%f",&R_ac);
R_a = (R_ab*R_ac)/(R_ab + R_bc + R_ac);
R_b = (R_ab*R_bc)/(R_ab + R_bc + R_ac);
R_c = (R_ac*R_bc)/(R_ab + R_bc + R_ac);
printf("the equivalent Star values are: \n");
printf("R_a = %.2f Ohms\n",R_a);
printf("R_b = %.2f Ohms\n",R_b);
printf("R_c = %.2f Ohms\n",R_c);
break;
case 0:
printf("\n\nAdios!!\n\n\n");
exit(0); // terminates the complete program execution
}
while (0) ; }
printf("\n\n\t\t\tThank you!\n\n\n");
return 0;
}
while(R_a = -0)
= is the assignment operator. This assigns -0 to R_a, and evaluates to the same falsy value, ending the loop.
Change the do ... while to an infinite loop, and break the loop when the value is in range.
while (1) {
printf("R_a = ");
if (1 != scanf("%f", &R_a))
exit(EXIT_FAILURE);
if (R_a > 1000000) {
fprintf(stderr, "Number too high.\n");
} else if (R_a < 1000) {
fprintf(stderr, "Number to low.\n");
} else {
break;
}
}

binary tree for sorting and search on c program

So i have a program to data the users input.
in this program i want to make some function
to ask the user for the product coming in
to display the history of data coming in by sorting by date.
to ask the user for the product coming out
to display the history of data coming out by sorting by date.
to search a specific product data by calling the code
to display all the data, the data is sorted by date and then the weight is data coming in minus data coming out
actually i have made a complete program of this, but the teacher updated the assignment. in the previous assignment i mostly use array instead of pointer and for sorting i use recursive bubble sort.
For now i need someone's help to make a sort by date using binary tree and search by product code using binary tree
Note : i must use binary tree because that's the assignment my teacher gave me
assignments are :
have a function with address argument
have a function with array argument
have function with argument as address to a structure
have a function with structure argument
add node to linked list/stack/queue/tree
read/delete node from linked list/stack/queue/tree.
Honestly i still understand linked list/stack/queue/tree. i thought to make a linked list i just change my array to a pointer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct {
int kode;
int amount;
char variety[20];
int weight;
int date;
}data;
data *innData;
data *outtData;
int menu;
int i;
int pointIn = 0, pointOut=0;
int amount = 0;
char variety[5][20] = {"Fish", "Crab", "Squid", "Clam", "Lobster"};
void sortDate(data *list, int range);
void back_menu();
void input();
void inputHistory();
void output();
void outHistory();
//void sort
//void calculateWeight
//void search();
//void showAll();
int main(){
innData=(data *)malloc(100*sizeof(data));
outtData=(data *)malloc(100*sizeof(data));
do {
printf(" ---------------- MARINE PRODUCT STOCK PROGRAM ---------------");
printf( " \n\nMAIN MENU :\n");
printf( "___________________________________________________________________\n\n");
printf( " 1. Input Product\n\n"); //data that the user input
printf( " 2. Entered History\n\n"); //show the history of the entered data by sorting the date
printf( " 3. Output Product\n\n"); //data that the user take out
printf( " 4. Exited Product\n\n");//show the history of the exited data by sorting the date
printf( " 5. Search Product\n\n"); //show the specific product by calling the code of the product
printf( " 6. Show All Product\n\n");
printf( " _____________________________\n\n");
printf( " choose (1 - 6) : ");
scanf ("%d", &menu);
if (menu < 1 || menu > 2) {
system("cls");
printf ("Please select the number between 1-2\n");
back_menu();
}
switch(menu) {
case 1:
input();
break;
case 2:
inputHistory();
break;
case 3:
output();
break;
case 4:
outHistory();
break;
// case 5:
// search(); // this function is used to search specific product by entering the code
// break;
// case 6:
// showAll(); // this function is used to show all of the stock in the warehouse. but the weight = input-output
// break;
}
free(innData);
free(outtData);
}
while (menu != 6);
system("cls");
printf ("============ Thankyou for using our program ============");
return 0;
}
void input(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointIn + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (innData+pointIn)->variety, variety[code]);
(innData+pointIn)->kode = code;
printf("\tvariety\t\t : %s\n", (innData+pointIn)->variety);
printf("\t Weight\t : "); scanf(" %d", &(innData+pointIn)->weight );
printf("\t Date (YYYYMMDD)\t : ");scanf(" %d", &(innData+pointIn)->date);
pointIn++;
}
}
back_menu();
}
void inputHistory(){
system("cls");
printf("***** INPUT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (innData+i)->date,(innData+i)->kode, (innData+i)->variety,(innData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void output(){
int code;
system ("cls");
printf("================= INPUT MENU =================\n\n");
printf("Enter the number of items to be recorded : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for(i = 0; i < amount; i++){
printf("\n\nPRODUCT ORDER-%d",pointOut + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if(code < 0 || code > 4){
printf ("product with that number is not available, select number 0-4\n");
i--;
}
else {
strcpy( (outtData+pointOut)->variety, variety[code]);
(outtData+pointOut)->kode = code;
printf("\tvariety\t\t : %s\n", (outtData+pointOut)->variety);
printf("\tWeight\t : "); scanf(" %d", &(outtData+pointOut)->weight );
printf("\tDate (YYYYMMDD)\t : ");scanf(" %d", &(outtData+pointOut)->date);
pointOut++;
}
}
back_menu();
}
void outHistory(){
system("cls");
printf("***** EXIT STOCK DATE HISTORY ***** \n" );
printf("------------------------------------------------------------------\n");
printf("| DATE | CODE | NAME | WEIGHT | \n");
printf("------------------------------------------------------------------\n");
//call sort function here
for (i = 0; i < pointIn; i++){
printf(" %d %d %s %d \n", (outtData+i)->date,(outtData+i)->kode, (outtData+i)->variety,(outtData+i)->weight) ;
}
printf("------------------------------------------------------------------\n");
back_menu();
}
void back_menu(){
printf("\n\n\t\t\tPress any key to continue.....");
getch();
system("cls");
}

GPA scores program

I am supposed to write a program where the user is asked how many students there are in a class. Then, it asks for the GPA of each of those students. In the end, it is supposed to display number of students with each GPA score. So far this is what i have, but it doesn't seem to count properly.
#include <stdio.h>
int main(void){
int cnt1, cnt2, cnt3, cnt4, student, numofsdts, GPA, GPAFreq[4];
printf("Enter number of students: ");
scanf("%d", &numofsdts);
student = 1;
while(student <= numofsdts){
printf("GPA of student number %d: ", student);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
}
else{
student++;
}
if(student == numofsdts + 1)
break;
if(GPAFreq[1])
cnt1++;
else if(GPAFreq[2])
cnt2++;
else if(GPAFreq[3])
cnt3++;
else if(GPAFreq[4])
cnt4++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}
Set int cnt1 = 0, cnt2 = 0 etc. (they are not nullified by default, just have some garbage [like a rented room not cleaned explicitly...]).
Also:
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue; // skip the rest of the loop body
}
Or a slightly cleaner approach (in full):
#include <stdio.h>
int main(void){
int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;
int numofsdts, GPA;
printf("Enter number of students: ");
scanf("%d", &numofsdts);
students = 0;
while(students <= numofsdts){
printf("GPA of student number %d: ", students + 1);
scanf("%d", &GPA);
if(GPA < 1 || GPA > 4){
printf("invalid number \n");
continue;
}
if(GPA == 1)
cnt1++;
else if(GPA == 2)
cnt2++;
else if(GPA == 3)
cnt3++;
else if(GPA == 4)
cnt4++;
students++;
}
printf("GPA 1: %d students \n", cnt1);
printf("GPA 2: %d students \n", cnt2);
printf("GPA 3: %d students \n", cnt3);
printf("GPA 4: %d students \n", cnt4);
}
There are multiple errors here. The first is that cnt1-4 have to be initialized prior to being added to. The second is that C uses zero indexing, so GPAFreq[4] is not accessing the fourth element of your array (which would be GPAFreq[3].
The third is that your if statement isn't doing what you think it is. It is evaluating the values inside of your array as boolean variables, i.e. 0 is false, anything else is true. A better approach is to do this:
GPAFreq[GPA - 1] += 1;
This will be counting the frequencies in each of the indices of the array. Then to print them, you just access GPAFreq and no longer need the cnt variables.

Making a menu driven program, errors

Beginner to C and doing an assignment for a course. Fixed what I think needed to be fixed, but my menu will only go to part A, but not B, C, or D. It quits fine as well. No errors, wondering what is wrong with my code.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH flush()
// Prototype Functions Here
void highestNumber(int, int, int);
void lowestNumber(int, int, int);
void displayAverage(int, int, int);
void displayMenu();
void flush();
char getUserChoice();
main() {
char userSelection;
int number1 = 0, number2 = 0, number3 = 0;
do {
userSelection = getUserChoice(); // Gets/DisplaysMenu
switch (userSelection) {
case 'A': // Enter a number
printf("Enter a number 1: ");
scanf("%i", &number1);
printf("Enter a number 2: ");
scanf("%i", &number2);
printf("Enter a number 3: ");
scanf("%i", &number3);
break;
case 'B': // Display Highest Number Entered
printf("In Case B");
highestNumber;
break;
case 'C': // Display Lowest Number entered
printf("In Case C");
lowestNumber;
break;
case 'D': // Display Average of Numbers entered
printf("In Case D");
displayAverage;
break;
case 'Q': // Quit the program
printf("You have quit the program\n");
PAUSE;
break;
default: // Invalid Selection
printf("Invalid selection...try again!\n");
PAUSE;
break;
} // end switch
} while (userSelection != 'Q');
PAUSE;
} // end of main
//==============
void highestNumber(int number1, int number2, int number3) {
if (number1 > number2 && number1 > number3) {
printf("The highest number is: %i", number1);
}
else if (number2 > number1 && number2 > number3) {
printf("The highest number is: %i", number2);
}
else if (number3 > number2 && number3 > number1) {
printf("The highest number is: %i", number3);
}
} //end highest number
void lowestNumber(int number1, int number2, int number3) {
if (number1 < number2 && number1 < number3) {
printf("The lowest number is: %i", number1);
}
else if (number2 < number1 && number2 < number3) {
printf("The lowest number is: %i", number2);
}
else if (number3 < number2 && number3 < number1) {
printf("The lowest number is: %i", number3);
}
} // end lowest number
void displayAverage(int number1, int number2, int number3) {
int average = (number1 + number2 + number3) / 3;
printf("The average of the three numbers you entered is: %i", average);
} // display average
void displayMenu() {
CLS;
printf("\n===============================\n");
printf("========== MAIN MENU ==========\n");
printf("===============================\n");
printf("A. Enter a number\n");
printf("B. Display Highest Number entered\n");
printf("C. Display Lowest Number entered\n");
printf("D. Display Average of Numbers entered\n");
printf("Q. Quit the program\n");
printf("Enter your choice: ");
} // end displayMenu
void flush() {
while (getchar() != '\n');
} // end flush
char getUserChoice() {
char result;
displayMenu();
scanf("%c", &result); FLUSH;
result = toupper(result);
return result;
} // end getUserChoice
the following code should perform as you want.
Caveat: there may be some details that you would like to modify such as uncommenting the calls to getchar()
The following code has a number of constraints built it, like must enter the 3 numbers before trying to do any operations on those numbers.
The following code does not use non-portable calls to the shell.
the data is kept locally in the main() function and passed to each of the sub functions that need it.
Notice the function that changes the data is passed pointers to the data so the sub function can change that data.
useless macros were eliminated
the function: flush() was renamed for clarity as to what it does
appropriate error checking added
commented out unneeded if() statements
expanded flushStdin() to allow for either EOF or '\n'
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Prototype Functions Here
void enterNumber (int*, int*, int*); // pass address so function can update
void highestNumber (int, int, int);
void lowestNumber (int, int, int);
void displayAverage(int, int, int);
void displayMenu ( void ); // corrected prototypes
void flushStdin ( void );
char getUserChoice ( void );
int main( void ) // only two valid signatures for main()
// this is one of them
{
char userSelection;
int number1; // added local data variables
int number2;
int number3;
int gotSelections = 0; // so cannot try to work with uninitialized data
do
{
userSelection = getUserChoice(); // Gets/DisplaysMenu
switch (userSelection)
{
case '1': // Enter a number
enterNumber( &number1, &number2, &number3 ); // pass expected parameters
gotSelections = 1;
break;
case '2': // Display Highest Number Entered
if( gotSelections )
{ // then data initialized
highestNumber( number1, number2, number3 ); // pass expected parameters
}
else
{ // else tried to pass unitialized data
printf( "must enter numbers before gathering Statistics\n" );
}
break;
case '3': // Display Lowest Number entered
if( gotSelections )
{ // then data initialized
lowestNumber( number1, number2, number3 ); // pass expected parameters
}
else
{ // else tried to pass unitialized data
printf( "must enter numbers before gathering Statistics\n" );
}
break;
case '4': // Display Average of Numbers entered
if( gotSelections )
{ // then data initialized
displayAverage( number1, number2, number3 );
}
else
{ // else tried to pass unitialized data
printf( "must enter numbers before gathering Statistics\n" );
}
break;
case 'Q': // Quit the program
printf("You have quit the program\n");
//system( "pause" );
break;
default: // Invalid Selection
printf("Invalid selection...try again!\n");
//system( "pause" );
break;
} // end switch
flushStdin();
//getchar();
} while (userSelection != 'Q');
//system( "pause" );
//flushStdin();
getchar();
} // end of main
void enterNumber(int * pNumber1, int *pNumber2, int *pNumber3)
{
printf("Enter a number 1:\n ");
if( 1 != scanf("%i", pNumber1) )
{
fprintf( stderr, "scanf for number1 failed" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
printf("Enter a number 2:\n ");
if( 1 != scanf("%i", pNumber2) )
{
fprintf( stderr, "scanf failed for number2" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
printf("Enter a number 3:\n ");
if( 1 != scanf("%i", pNumber3) )
{
fprintf( stderr, "scanf for number3 failed" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
} //end enter number
void highestNumber(int number1, int number2, int number3)
{
if (number1 > number2 && number1 > number3)
{
printf("The highest number is: %i\n", number1);
}
else if (number2 > number1 && number2 > number3)
{
printf("The highest number is: %i\n", number2);
}
else //if (number3 > number2 && number3 > number1)
{
printf("The highest number is: %i\n", number3);
}
} //end highest number
void lowestNumber(int number1, int number2, int number3)
{
if (number1 < number2 && number1 < number3)
{
printf("The lowest number is: %i\n", number1);
}
else if (number2 < number1 && number2 < number3)
{
printf("The lowest number is: %i\n", number2);
}
else //if (number3 < number2 && number3 < number1)
{
printf("The lowest number is: %i\n", number3);
}
} // end lowest number
void displayAverage(int number1, int number2, int number3)
{
int average = (number1 + number2 + number3) / 3;
printf("The average of the three numbers you entered is: %i\n", average);
} // display average
void displayMenu()
{
//system( "cls" );
puts( "\033[H \033[J"); // \033 is octal value for 'escape'
printf("\n===============================\n");
printf("========== MAIN MENU ==========\n");
printf("===============================\n");
printf("1. Enter a number\n");
printf("2. Display Highest Number entered\n");
printf("3. Display Lowest Number entered\n");
printf("4. Display Average of Numbers entered\n");
printf("Q. Quit the program\n");
printf("Enter your choice: ");
} // end displayMenu
void flushStdin()
{
int ch;
while ( (ch = getchar()) != EOF && '\n' != ch );
} // end flush
char getUserChoice()
{
char result;
displayMenu();
if( 1 != scanf(" %c", &result) )
{
fprintf( stderr, "scanf for menu entry failed" );
flushStdin();
getchar();
exit( EXIT_FAILURE );
}
flushStdin();
//getchar();
result = (char)toupper((int)result);
return result;
} // end getUserChoice

Having troubles with nested while loops

The goal is to assign the average to different players based on their uniform number. The problem is that it keeps skipping the second printf and the characters from the switch statement aren't working. I'm sure it's a pretty simple error on my part, but I just can't seem to find it.
int main(){
float ab;
float hits;
int un;
char pa;
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
while( un!= -1)
{
printf("Please enter either an H for a hit or an O for a out, enter E to stop. \n");
scanf("%c%*c", &pa);
while(pa != 'E')
{
switch (pa)
{
case 'h':
case 'H':
ab += 1;
hits +=1;
break;
case 'o':
case 'O':
ab+=1;
break;
default:
printf("Error: Please insert an O or H \n");
break;
}
float average = (ab/hits);
printf("Player %d's score is equal to: %d \n", un, average);
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
}
}
return 0;
}
Your loop nesting wasn't quite correct, your scanf calls would hang, you needed to preinitialize ab and hits, and your final printf had an incorrect format.
Here's the corrected code [please pardon the gratuitous style cleanup]:
#include <stdio.h>
int
main()
{
float ab;
float hits;
int un;
char pa;
while (1) {
printf("Please enter the player number, or -1 to exit.\n");
#if 0
scanf("%d%*c \n", &un);
#else
scanf(" %d", &un);
#endif
if (un == -1)
break;
ab = 0;
hits = 0;
printf("Please enter either an H for a hit or an O for a out, enter E to stop.\n");
while (1) {
#if 0
scanf("%c%*c", &pa);
#else
scanf(" %c", &pa);
#endif
if ((pa == 'E') || (pa == 'e'))
break;
switch (pa) {
case 'h':
case 'H':
ab += 1;
hits += 1;
break;
case 'o':
case 'O':
ab += 1;
break;
default:
printf("Error: Please insert an O or H\n");
break;
}
}
float average = (ab / hits);
#if 0
printf("Player %d's score is equal to: %d\n", un, average);
#else
printf("Player %d's score is equal to: %g\n", un, average);
#endif
}
return 0;
}

Resources