Learn C · lesson 16 of 60 · about 9 minutes
Project: Health Score
The report ends with a health score. Work it out, give it a grade with else if, and pick the last words with switch.
What you'll learn
- Grade a score with else if, highest band first
- Test every band at its edge
- Pick a message for each grade with switch
The plan
1. The score is free_kib / 50, minus 10 for each warning
2. The grade is A from 80, B from 60, C from 40, and F below that
3. Print the score and the grade
4. Pick the last words with switch: A gets Running smoothly., B and C share Keep an eye on it., and anything else gets Time for a clean-up.
Check the bands from the top. Only the first true branch runs, so each else if only needs its lower edge.
Grading a score
#include <stdio.h>
int main(void) {
int free_kib = 3000;
int warnings = 1;
int score = free_kib / 50 - warnings * 10;
char grade;
if (score >= 80) {
grade = 'A';
} else if (score >= 60) {
grade = 'B';
} else if (score >= 40) {
grade = 'C';
} else {
grade = 'F';
}
printf("Health score: %d, Grade: %c\n", score, grade);
return 0;
}Output
Health score: 50, Grade: CTest every edge
Each band starts at an exact score, so test those first: 80, 60 and 40, then a score just below each one. A grade that's wrong at its edge is the most common bug in code like this.
Tip
A char holds one letter, like 'A', which makes the grade easy to switch on. return 1; from main is how a C program reports that something went wrong, which you'll use for bad input later.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.