C - Write program to calculate class grade average

Requirements

Write a program to calculate the average grade for the students in each of an arbitrary number of classes.

Output the student grades for each class followed by the average for that class.

Demo

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>

int main(void)
{
  const size_t cCount = 5;                  // Number classes
  const size_t sCount = 7;             // Maximum number of students in a class
  char answer = 'N';

  int grades[cCount][sCount];                     // Stores the grades
  size_t students[cCount];                               // Stores the number of students in each class

  for (size_t i = 0; i < cCount; ++i)
  {/*from w ww.j  a v a2s . c o  m*/
    printf("Enter the grades for students in class %zd.\n", i + 1);
    students[i] = 0;                                   // Student count within a class
    while (true)
    {
      printf("Enter the integer grade for student %zd: ", students[i] + 1);
      scanf("%d", &grades[i][students[i]]);
      if (++students[i] == sCount)                // Increment and check student count
      {
        printf("Class %zd complete.", i + 1);
        break;
      }
      printf("Any more students in class %zd (Y or N): ", i + 1);
      scanf(" %c", &answer);
      if (toupper(answer) == 'N')
        break;
    }
  }
  printf("\n");
  for (size_t i = 0; i < cCount; ++i)
  {
    int class_total = 0;
    printf("Student grades for class %zd are:\n", class_total + 1);
    for (size_t student = 0; student < students[i]; ++student)
    {
      class_total += grades[i][student];
      if ((student + 1) % 6 == 0)
        printf("\n");
      printf("%5d", grades[i][student]);
    }
    printf("\nAverage grade for class %zd is %.2lf\n", i + 1, (double)class_total / students[i]);
  }
  return 0;
}

Result

Related Exercise