Lesson 9 of 50 beginner

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

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. 1. int score; cin >> score; — we read the student's test score.
  2. 2. if (score >= 90) grade = 'A'; — we check the HIGHEST grade first. If the score is 90 or above, it is an A.
  3. 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. 4. else if (score >= 70) grade = 'C'; — same idea. If we reach here, we know score < 80. So this catches 70-79.
  5. 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. 6. switch (direction) — we check the direction variable against specific character values.
  7. 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. 8. default: — like else for switch. If no case matches, this runs.
  9. 9. if (n > 0 && n % 2 == 0) — this combines two conditions with && (AND). Both must be true: n must be positive AND even.
  10. 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

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero