Learn C++ · lesson 17 of 61 · about 9 minutes
Project: The Final Score
The adventure ends with a score. Work it out, give it a rank with else if, and pick the last words with switch.
What you'll learn
- Rank a score with else if, highest band first
- Test every band at its edge
- Pick a message for each rank with switch
The plan
1. The score is health + gold × 2
2. The rank is S from 155, A from 125, B from 95, and C below that
3. Print the score and the rank
4. Pick the last words with switch: S gets Legendary!, A and B share A fine adventure., and anything else gets Better luck next time.
Check the bands from the top. Only the first true branch runs, so each else if only needs its lower edge.
Ranking a score
#include <iostream>
int main() {
int health = 65;
int gold = 15;
int score = health + gold * 2;
char rank;
if (score >= 155) {
rank = 'S';
} else if (score >= 125) {
rank = 'A';
} else if (score >= 95) {
rank = 'B';
} else {
rank = 'C';
}
std::cout << "Score: " << score << ", Rank: " << rank << "\n";
}Output
Score: 95, Rank: BTest every edge
Each band starts at an exact score, so test those first: 155, 125 and 95, then a score just below each one. A rank that's wrong at its edge is the most common bug in code like this.
Tip
A char holds one letter, like 'S', which makes the rank easy to switch on.
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.