Hello aqshaf... the problem here is that you calculate your average in the if statement and test for average's value in the else if portion. Remember that if the if is executed, it will skip right over else if. Else if is only executed if the "if statement" is false.
So what you need to do is calculate average first, then go into your if else statements. If you calculate average in the if statement, it will test counter being greater than zero (don't test for not equal to zero because we want it to fail if counter is some how negative) and calculate average, then skip right over else if statements that test its value for grades.
Here is your program fixed up a bit. Notice 2 things...
1) We make your tests > 0 not != 0 because we don't want it to succeed if counter is ever negative.
2) We first calculate average, then we go into an if else statement to test that average variable.
cpp
//example 4.22
#include<stdio.h>
int main ()
{
int sum = 0, marks = 0, counter = 1;
float average = 0;
printf( "Please enter the marks obtained or -1 to quit:\n");
scanf( "%d", &marks );
while ( marks != -1 )
{
sum = sum + marks;
counter ++;
printf( "Please enter the marks obtained or -1 to quit:\n");
scanf( "%d", &marks );
}
// Calculate average before going into an if statement test
if( counter > 0 )
{
average = (float) sum/counter;
printf( " The average grade marks are: %.2f ", average);
}
// Again test we have some scores and if so, it means
// we have an average calculated too
if (counter > 0) {
// Now go into testing average
if ( average >= 80.00 )
printf( "The average grade is 'A'.\n");
else if( average < 80.00 && average >= 70.00 )
printf( "The average grade is 'B'. \n");
else if( average < 70.00 && average >= 60.00 )
printf( "The average grade is 'C'. \n");
else if( average < 60.00 && average >= 40.00 )
printf( "The average grade is 'D'.\n");
else
printf( "\nThe average grade is 'F'. \n");
}
printf( "You enter: %d times\n", counter);
return 0;
}
Notice I test counter twice here, one to make sure that we have values to find an average and the second is to make sure that we did calculate an average. We could have tested if average was still equal to 0, but in theory you could have an average of zero and still be legitimate.
Enjoy!
"At DIC we be average calculating and if else testing code ninjas... else we would be just plain old nerds"