Averages

The report card needs each student's average: the sum of their points divided by the number of tests, 3. The sum is the pattern from the lesson on loops: a variable that starts at 0, and a loop that adds each value to it.

A new function, average(), will compute it for one student. It gets the whole student as its parameter: double average(Student student). The type is Student with a capital S, and the parameter is student with a small one. C tells capital and small letters apart, so for C, these are two different names. As you know from the lesson on structures, a structure parameter is a copy: the function gets its own copy of the student, with the name and all the points. That's fine here, because it only reads them. It returns a decimal number, so its type is double.

Watch out for whole-number division: 125 / 3 is 41, and the decimals are lost. The result has decimals when at least one of the numbers is a double. The easiest way is to add up in a double variable right away:

int temperatures[] = {18, 21, 23, 19};
double sum = 0;
for (int i = 0; i < 4; i++) {
    sum += temperatures[i];
}
printf("Average temperature: %.2f\n", sum / 4);
Average temperature: 20.25

One more trap: return belongs after the loop. Inside the loop, it would end the function in the very first pass, and the average would be computed from the first test only. And without a return after the loop, the program doesn't even compile: non-void function does not return a value in all control paths.

Write the new function above print_report(), which will call it. If it were below, the compiler wouldn't know it yet at the place of the call, and it would report an error:

main.c:17:27: error: call to undeclared function 'average'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]

You can call a function that returns a value right inside printf: average(students[i]) gives the average of the student with index i, and %6.1f prints it with one decimal place, in 6 characters.

Instructions

Above print_report(), write a function double average(Student student) that adds up the three numbers in student.points and returns their sum divided by 3.

In print_report(), replace the printf("\n"); at the end of each student's line with printf("%6.1f\n", average(students[i]));, which prints the student's average before it ends the line. The program prints:

MATH RESULTS
Adam        42  38  45  41.7
Emma        36  33  38  35.7
Finn        48  50  47  48.3
Jack        14  22  17  17.7
Lucy        27  40  41  36.0

If Adam has 41.0, you're dividing whole numbers. If he has 14.0, there's a return inside the loop.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/7