In: Computer Science
MUST BE DONE IN C (NOT C++)
In this program we will calculate the average of x students’ grades (grades will be stored in an array). To do so, please follow these guidelines:
- Your program should ask the user for the number of students that are in the class. This number should help you declare your array.
- Use the function seen in class to scan the grades of the array. In other words, we will populate the array with a function.
- When done, use the printing function seen in class to make sure all grades were scanned correctly.
- Then, call the “average” function. This function will receive two parameters, the array’s length and the array. Inside the function, you will calculate the average (using a loop) and you will return the average.
- In main, you will received this returned value and print it.
C CODE :
#include <stdio.h>
float average(int a[], int x)
{
int sum = 0;
float avg = 0;
for(int i = 0; i < x; i++)
{
sum += a[i]; // do sum of the grades
}
avg = (float) sum / x; // then divide it by size to calculate
average
return avg; // return average
}
int main()
{
int x;
printf("Enter the number of students in the class : ");
scanf("%d", &x); // read the number of students
int a[x];
printf("Enter the grades of each person in the class : ");
for(int i = 0; i < x; i++)
{
scanf("%d", &a[i]); // read the grades of the students
}
printf("The enteres grades are : ");
for(int i = 0; i < x; i++)
{
printf("%d ", a[i]); // print the grades to confirm
}
float avg = average(a, x);
printf("\nAverage of the grades are : %f", avg); // print the
average of the grades
return 0;
}
SCREENSHOT OF THE C CODE :