Bonus Points
Finn and Jack helped to run the school's math competition, and the teacher rewards them: they each get 3 bonus points for every test. But no test can have more than 50 points, because that's the most a test could give.
This time, the function changes a student. If it got the student as Student student, it would change only its own copy, and the student in the array would stay the same. That's why it gets a pointer to the student: Student *student, the address of the student in the array. Through it, the function changes the original. You reach a structure's members through a pointer with an arrow, ->: student->points[i] means the same as (*student).points[i]. For example, a game where a player can have 5 lives at most:
#include <stdio.h>
typedef struct {
char name[20];
int lives;
} Player;
void add_lives(Player *player, int extra) {
player->lives += extra;
if (player->lives > 5) {
player->lives = 5;
}
}
int main(void) {
Player players[] = {
{"Tom", 2},
{"Sara", 4},
};
add_lives(&players[0], 2);
add_lives(&players[1], 2);
printf("%s: %d lives\n", players[0].name, players[0].lives);
printf("%s: %d lives\n", players[1].name, players[1].lives);
return 0;
}Tom: 4 lives
Sara: 5 livesWhen you call the function, you give it the address of a student with &: &students[3] is the address of the student with index 3, Jack. Typical mistakes:
- Without the
&, the compiler reportserror: passing 'Student' to parameter of incompatible type 'Student *'; take the address with &. The end of the message even tells you what to do. - With a dot instead of the arrow,
student.points[i], it reportserror: member reference type 'Student *' is a pointer; did you mean to use '->'? - With
const Student *student, the function isn't allowed to change the student, and the compiler reportserror: cannot assign to variable 'student' with const-qualified type 'const Student *'.
The calls go in main(), above print_report(students, count);: first the points change, then they're printed. The other way round, the old points would be printed.
Instructions
Under print_report() (above main()), write a function void add_bonus(Student *student, int bonus) that adds bonus to each of the student's three test scores in a loop.
In main(), above the call of print_report(), give the bonus to Finn and Jack: add_bonus(&students[2], 3); and add_bonus(&students[3], 3);. Jack now has 3 more points in each test, and with an average of 20.7, he gets a D:
Jack 17 25 20 20.7 DIf nothing has changed, you call add_bonus() after print_report(). But Finn now has 51 and 53 points, more than a test could give. You'll fix that in the next step.
Change add_bonus(): if a test has more than 50 points after the addition, set it to 50. Then the results look like this:
MATH RESULTS
Adam 42 38 45 41.7 B
Emma 36 33 38 35.7 C
Finn 50 50 50 50.0 A
Jack 17 25 20 20.7 D
Lucy 27 40 41 36.0 C
Best: Finn (average 50.0)Start programming for free
5/7