Else-If Ladder
Sometimes two choices are not enough. A temperature can be freezing, cold, mild or hot. To handle more than two cases, put else if between the if and the final else. This is called an else-if ladder.
#include <iostream>
using namespace std;
int main() {
int temperature = 18;
if (temperature < 0) {
cout << "Freezing" << "\n";
} else if (temperature < 15) {
cout << "Cold" << "\n";
} else if (temperature < 25) {
cout << "Mild" << "\n";
} else {
cout << "Hot" << "\n";
}
return 0;
}
Output:
Mild
C++ checks the conditions from top to bottom. The first condition that is true wins: its body runs, and C++ skips all the rest. If no condition is true, the final else runs.
Here is how C++ handled 18:
| Condition | Result |
|---|---|
temperature < 0 | false, go on |
temperature < 15 | false, go on |
temperature < 25 | true, print Mild and stop |
Look at the second condition. It is only temperature < 15. It does not also check temperature >= 0. It does not need to: C++ only reaches that line when the first condition was false, so the temperature is already 0 or more. Each step of the ladder knows that every condition above it was false.
The order matters
Because the first true condition wins, a ladder in the wrong order gives wrong answers. Here the < 25 check comes before the < 0 check:
int temperature = -5;
if (temperature < 25) {
cout << "Mild" << "\n";
} else if (temperature < 0) {
cout << "Freezing" << "\n";
}
Output:
Mild
-5 is less than 25, so the first body runs and the ladder stops. The Freezing line can never run, because every number below 0 is also below 25. The compiler does not warn you about this. When a ladder gives a wrong answer, read it from the top and ask, for each line: "which values were already caught above?"
You can also build a ladder from the top down with >=. Then you start with the highest range, like score >= 90, and go down from there.
In the exercise, turn a score into a grade letter with an else-if ladder.