1

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);
}
1
  • 4
    Array subscripts for 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 from scanf() to ensure you got actual data each time. Commented Oct 6, 2014 at 20:49

3 Answers 3

3

Your for loops are not correct. Specifically indices start at 0, e.g. instead of

for(n=1; n<=5; n++) {

use

for(n = 0; n < 5; n++) {

The computation of the average is correct. It's just the wrong indexing before that.

Sign up to request clarification or add additional context in comments.

Comments

2

Array indexes start at 0 and not 1 in C. When you are calculating the average you get this right but not when you are doing the loops to enter in the data. Therefore when you have:

for(n=1; n<=5; n++){
    printf("Enter grade %d between 0 and 100: ",n);
    scanf("%f", &grade[n]);
}

you end up running 1 past the end of the the array.

Instead you should start your loop at 0:

for(n=0; n<5; n++){
    printf("Enter grade %d between 0 and 100: ",n);
    scanf("%f", &grade[n]);
}

The second loop is the same. As noted in the comments you have to then take into account the index being one lower when printing the student number in the second loop:

printf("%d\t\t%.1f\n\n", n+1,grade[n]);

1 Comment

To get the same output as before he needs to printf n+1, not n.
0

You can also put calculation of avg inside 2nd loop.

avg = 0;
for(n=0; n<5; n++){
    printf("%d\t\t%.1f\n\n",n ,grade[n]);
    avg += grade[n];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.