I'm still a total beginner and this program is giving me some trouble. Everything works fine up until the point where it calculates the average of inputted values that serve as elements for the array grade[ ].
The output is a table with student number 1 through 5 listed beside each student's inputted grade. I can display the student number and grades just fine but the program cannot seem to calculate average properly. Please help?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main()
{
float grade[5];
int n;
for(n=1; n<=5; n++){
printf("Enter grade %d between 0 and 100: ",n);
scanf("%f", &grade[n]);
}
printf("\nStudent\t\tGrade\n");
for(n=1; n<=5; n++){
printf("%d\t\t%.1f\n\n",n ,grade[n]);
}
printf("--------------------\n");
float avg = (grade[0] + grade[1] + grade[2] + grade[3] + grade[4]) / 5;
printf("Average Grade:\t%.1f", avg);
}
float grade[5];run from 0 to 4, not 1 to 5. So, you are writing out of bounds in your array when scanning and printing, leading to undefined behaviour. Your average uses an unintialized variable (grade[0]). You should be checking the return value fromscanf()to ensure you got actual data each time.