The Best Student
Who did best this term? You know how to find the largest value from the lesson on arrays: remember the first element, and in a loop, check whether any of the others is larger. This time, you compare the students' averages, and you want to know who it is, not only the highest average. So the function remembers the whole student and returns them: a function can return a structure, just like a number. For example, the longest jump in a competition:
#include <stdio.h>
typedef struct {
char name[20];
int jump;
} Athlete;
Athlete longest_jump(const Athlete athletes[], int count) {
Athlete best = athletes[0];
for (int i = 1; i < count; i++) {
if (athletes[i].jump > best.jump) {
best = athletes[i];
}
}
return best;
}
int main(void) {
Athlete athletes[] = {
{"Amy", 412},
{"Ben", 455},
{"Chloe", 430},
};
Athlete winner = longest_jump(athletes, 3);
printf("Longest jump: %s, %d cm\n", winner.name, winner.jump);
return 0;
}Longest jump: Ben, 455 cmThe variable best starts with the first athlete, so the loop can start at index 1. Comparing with > (not >=) means that in a tie, whoever comes first in the array wins.
Notice best = athletes[i];. An array can't be assigned with =, but a structure can: all its members are copied, even an array inside it. So best holds a copy of the athlete, and the function returns that copy. To read the name and the jump, that's all you need.
In your function, compare the averages: average(students[i]) > average(best). In print_report(), store the result in a variable, for example Student best = best_student(students, count);, and print its name and average: best.name and average(best).
Instructions
Under grade() (above print_report()), write a function Student best_student(const Student students[], int count) that returns the student with the highest average.
At the end of print_report(), after the loop (not inside it), print the name and the average of the best student:
Best: Finn (average 48.3)If Jack appears instead, your comparison is the wrong way round.
Start programming for free
4/7