4.2 — else and else if
Read one box at a time. No rush.
else: otherwise#
else runs when the if condition is false.
C++
int age {};std::cin >> age; if (age >= 18){ std::cout << "You can vote.\n";}else{ std::cout << "Not yet!\n";}Exactly one of the two blocks runs. Never both.
else if: more choices#
Chain more questions with else if. C++ checks them from top to bottom and runs the first one that is true.
C++
int score { 72 }; if (score >= 90){ std::cout << "Grade A\n";}else if (score >= 70){ std::cout << "Grade B\n";}else if (score >= 50){ std::cout << "Grade C\n";}else{ std::cout << "Keep practising!\n";}Output
Grade BKey idea
Only the first true branch runs. Score 72 is also >= 50, but C++ already stopped at "Grade B".
Nesting#
You can put an if inside another if:
C++
if (isLoggedIn){ if (isAdmin) { std::cout << "Welcome, boss.\n"; } else { std::cout << "Welcome back.\n"; }}Tip
Too many nested ifs get hard to read. Often && can join them: if (isLoggedIn && isAdmin).
Tip: press ← / → to move between lessons, / to search.