Else-If Chains — Multiple Choices
When life gives you more than two options, else-if chains and switch-case have you covered!
Open interactive version (quiz + challenge)Real-world analogy
An else-if chain is like a vending machine. You press button A1 — if it matches a Coke, out comes Coke. Else if A2 matches Sprite, out comes Sprite. Else if A3 matches water, out comes water. Else, the machine says 'Invalid selection.' The machine checks each button in order and stops at the first match!
What is it?
Else-if chains let you check multiple conditions in sequence, executing the code block for the FIRST condition that is true. Switch-case is an alternative that checks one variable against a list of specific values. Both let your code handle many different scenarios cleanly.
Real-world relevance
Multi-way decisions are everywhere! A weather app shows different icons based on temperature ranges. A restaurant menu app applies different discounts based on order total. Video games assign difficulty levels based on player stats. In CP, you constantly classify input into categories — 'print YES if this, NO if that, MAYBE if something else.'
Key points
- The Else-If Chain — Checking Many Conditions — When you have more than two possible outcomes, use else-if chains: if (cond1) { } else if (cond2) { } else if (cond3) { } else { }. Conditions are checked from TOP to BOTTOM, and the FIRST one that is true runs. After that, ALL remaining conditions are skipped. The final 'else' is optional but catches anything that did not match.
- Order Matters! — Since conditions are checked top to bottom, the order you put them in is crucial. For example, in a grading system: if you check (score >= 60) before (score >= 90), everyone with 90+ would get the 60+ result! Always check from most specific to least specific. Think of it like a water slide — you stop at the first pool you reach.
- The Grade Calculator — Classic Example — Here is the classic: if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'. Notice we check from highest to lowest. If score is 85, it fails the >= 90 check, then PASSES the >= 80 check, so it gets B. The remaining checks are skipped.
- Switch-Case — A Cleaner Way for Exact Values — When comparing ONE variable against specific values, switch-case is cleaner: switch(x) { case 1: do_something; break; case 2: do_other; break; default: fallback; }. Each 'case' checks if x equals that value. The 'break' is required to stop — without it, execution 'falls through' to the next case! 'default' is like 'else'.
- Break Is Mandatory in Switch! — Forgetting 'break' in a switch is a famous C++ bug. Without break, after matching one case, the code CONTINUES running into the next case! This is called 'fall-through.' Sometimes it is useful on purpose, but 99% of the time it is a bug. Always put break at the end of each case unless you have a very good reason not to.
- Switch Limitations — Only Integers and Characters — Switch-case only works with int, char, and enum types. You CANNOT use switch with strings, doubles, or ranges. For those, you must use if-else chains. In CP, switch is most useful for menu-style problems or when checking specific character values (like 'R', 'L', 'U', 'D' for directions).
- CP Pattern — Multiple Test Cases with Conditions — Many CP problems give you T test cases, and each one needs a different response based on conditions. The pattern is: read T, loop T times, read input, use if-else chain to determine the answer, print it. This combines loops (which we will learn soon) with conditional logic.
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
// Grade calculator with else-if chain
int score;
cin >> score;
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
cout << "Grade: " << grade << "\n";
// Switch-case: direction commands
char direction;
cin >> direction;
switch (direction) {
case 'U':
cout << "Moving Up\n";
break;
case 'D':
cout << "Moving Down\n";
break;
case 'L':
cout << "Moving Left\n";
break;
case 'R':
cout << "Moving Right\n";
break;
default:
cout << "Invalid direction\n";
break;
}
// CP problem: classify a number
int n;
cin >> n;
if (n > 0 && n % 2 == 0) {
cout << "Positive Even\n";
} else if (n > 0 && n % 2 != 0) {
cout << "Positive Odd\n";
} else if (n < 0) {
cout << "Negative\n";
} else {
cout << "Zero\n";
}
return 0;
}Line-by-line walkthrough
- 1. int score; cin >> score; — we read the student's test score.
- 2. if (score >= 90) grade = 'A'; — we check the HIGHEST grade first. If the score is 90 or above, it is an A.
- 3. else if (score >= 80) grade = 'B'; — this ONLY runs if the first check failed (score < 90). So if we get here, we know 80 <= score < 90.
- 4. else if (score >= 70) grade = 'C'; — same idea. If we reach here, we know score < 80. So this catches 70-79.
- 5. else grade = 'F'; — if NO condition was true, the score is below 60 and gets an F. The else is our safety net.
- 6. switch (direction) — we check the direction variable against specific character values.
- 7. case 'U': cout << "Moving Up\n"; break; — if direction is 'U', print the message and BREAK out. Without break, it would continue to the next case!
- 8. default: — like else for switch. If no case matches, this runs.
- 9. if (n > 0 && n % 2 == 0) — this combines two conditions with && (AND). Both must be true: n must be positive AND even.
- 10. else if (n > 0 && n % 2 != 0) — positive AND odd. By using else-if, we ensure only one category gets printed.
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
int score = 85;
if (score >= 60) {
cout << "D\n";
} else if (score >= 70) {
cout << "C\n";
} else if (score >= 80) {
cout << "B\n";
} else if (score >= 90) {
cout << "A\n";
} else {
cout << "F\n";
}
return 0;
}Need a hint?
What order are the conditions checked? Score 85 is >= 60, and also >= 70, >= 80... but which condition does the code check FIRST?
Show answer
The bug is that conditions are checked in the WRONG ORDER — from lowest to highest. Since 85 >= 60 is true, the code immediately prints 'D' and skips everything else! A score of 95 would also print 'D'! The fix is to reverse the order: check >= 90 first, then >= 80, then >= 70, then >= 60, then else for F. Always go from most restrictive to least restrictive.
Explain like I'm 5
Imagine you are at a theme park and the sign says: 'If you are taller than 150cm, ride the big roller coaster. Else if you are taller than 120cm, ride the medium coaster. Else if you are taller than 90cm, ride the kiddie coaster. Else, visit the playground.' You check from the top, and the FIRST one you qualify for is what you get!
Fun fact
The switch-case 'fall-through' behavior comes from the C language, created by Dennis Ritchie in the 1970s. He designed it to fall through on purpose because sometimes you WANT multiple cases to share code. But it has caused so many bugs that modern languages like Rust and Go require explicit 'fall-through' — C++ kept the old behavior for backward compatibility!
Hands-on challenge
Write a program that reads a score (0-100) and prints the grade: A (90-100), B (80-89), C (70-79), D (60-69), F (below 60). Also print a message: A='Excellent!', B='Great!', C='Good', D='Needs work', F='Study harder!'. Test with inputs 95, 82, 71, 55.
More resources
- Codeforces — Elephant (Codeforces)
- Switch Case in C++ Explained (YouTube)
- USACO Guide — Ad Hoc Problems (USACO Guide)