SMywane SMywane - 2 months ago 8
C Question

Programming C Loop Incorrect calculation

I am writing a C code that calculates the average of the marks. It asks the user to input the number of marks between 3 and 40. If the user doesn't input between 3 and 40, it asks again. It then asks for the mark percentages and adds it all up to calculate the average. Here's my code:

#include<stdio.h>
int main()
{
int number_marks,i, a=1;
float grade, total, average;

printf("Please enter the number of marks (between 3 and 40): ");
scanf("%d", &number_marks);

if(number_marks>3 || number_marks<40)
{
do{
printf("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf("%d",&number_marks);
}while(number_marks<3 || number_marks>40);
for(i=0;i<number_marks;i++)
{
printf("%d>",a++);
scanf("%f",&grade);
total=grade+grade+grade+grade+grade;
average= (total/number_marks);
}
}
printf("The average of all marks in this group is %.1f\n",average);
printf("Program Ended.");
return 0;
}


The problem is the output of the calculation. It seems that it outputs the final grade and does not calculate the average. There's the output:

Please enter the number of marks (between 3 and 40): 2
Invalid number, enter a number between 3 and 40 inclusive: 41
Invalid number, enter a number between 3 and 40 inclusive: 5
1>45
2>90
3>57
4>89
5>32
The average of all marks in this group is 32.0
Program Ended.

Answer

First of all your if statement is wrong because your have to check if the number is outside the 3-40 bounds, you need to use the <> in the opposite direction. So to correct this:

if(number_marks<3 || number_marks>40)
{
    do{
    printf("Invalid number, enter a number between 3 and 40 inclusive: ");
    scanf("%d",&number_marks);
    }
    while(number_marks<3 || number_marks>40);
}

Then in the part where you calculate the average:

1) why do you even use a++ ???? just use the i variable. it's common, proper and logical

2) total=grade+grade+grade+grade+grade; grade is always the same variable with one value no matter what you do. So here it will only add the last stored value five times and then divide it with 5. That's why you will always get the last grade as a result. The right way to do this is to update the total variable.

3) Finally the average= (total/number_marks); should be outside the loop. I also used (float)number_marks to make sure that the outcome of this calculation is always a float number.

Here is an example of how it should look like:

for(i=0;i<number_marks;i++)
{
    printf("%d>",(i+1));
    scanf("%f",&grade);
    total+=grade;
}
average = (total/(float)number_marks);
printf("The average of all marks in this group is %.1f\n",average);
printf("Program Ended.");
Comments