Grades
Every average gets a grade. The teacher gives it like this:
- an average of 45 or more: A
- 38 or more: B
- 30 or more: C
- 20 or more: D
- less than 20: F
That's a choice between several options, which is what else if is for. Put it in a function that gets the average and returns the grade. A function can have more than one return, and a condition decides which one runs. The grade is a letter, so the function returns a char: write char before its name, and return letters in single quotes, like 'A'. For example, T-shirt sizes:
#include <stdio.h>
char shirt_size(int height) {
if (height < 150) {
return 'S';
} else if (height < 175) {
return 'M';
} else {
return 'L';
}
}
int main(void) {
printf("%c\n", shirt_size(140));
printf("%c\n", shirt_size(160));
printf("%c\n", shirt_size(185));
return 0;
}S
M
LThe order of the conditions matters. The program tries them from the top and runs only the first one that's true. So each next condition is tried only when none of the earlier ones was true. Someone 140 cm tall also meets height < 175, but the program never gets to that condition. In grade(), start with the highest limit. If the first condition were avg >= 20, it would be true for Finn with 48.3 too, and he'd get a D.
Watch the limits as well: an average of exactly 38 is still a B, so the condition is avg >= 38, not avg > 38.
And watch the quotes: "A" in double quotes is a string, not a char, and the compiler reports an error:
main.c:21:16: error: incompatible pointer to integer conversion returning 'char[2]' from a function with result type 'char' [-Wint-conversion]On each line, you'll need the average twice: to print it and to work out the grade. So store it in a variable, double avg = average(students[i]);, and average() is called only once.
Instructions
Above print_report(), write a function char grade(double avg) that returns 'A' for an average of 45 or more, 'B' for 38 or more, 'C' for 30 or more, 'D' for 20 or more and 'F' otherwise.
In print_report(), store the student's average in a variable avg, and at the end of the line, print it, two spaces and the grade from grade(): printf("%6.1f %c\n", avg, grade(avg));. The program prints:
MATH RESULTS
Adam 42 38 45 41.7 B
Emma 36 33 38 35.7 C
Finn 48 50 47 48.3 A
Jack 14 22 17 17.7 F
Lucy 27 40 41 36.0 CIf Finn has a D, check the order of the conditions: the highest limit comes first.
Start programming for free
3/7