Conditionals (if-else & switch)

⚡ C++ Lesson 5 Beginner

Conditionals control code paths based on boolean evaluations. C++ supports standard if-else logic, ternary operators, and modern switch statements.

1 If-else Logic & Switch Fall-through

Conditionals direct flow paths. In switch-case blocks, omitting a `break` statement causes execution to "fall through" and execute subsequent case blocks without validation.

2 Conditional Codes

Let's run a program evaluating conditions and checking switch fall-throughs:

C++ — Conditionals ▶ Run Code
#include <iostream>

int main() {
    int score = 85;

    if (score >= 90) {
        std::cout << "Grade: A\n";
    } else if (score >= 80) {
        std::cout << "Grade: B\n";
    } else {
        std::cout << "Grade: F\n";
    }

    // Ternary operator evaluation
    std::string passed = (score >= 50) ? "Yes" : "No";
    std::cout << "Passed: " << passed << "\n";

    // Switch case with fall-through
    char grade = 'B';
    switch (grade) {
        case 'A':
            std::cout << "Perfect score!\n";
            break;
        case 'B':
            std::cout << "Nice progress!\n";
            // No break! Fall-through will execute case 'C' too!
        case 'C':
            std::cout << "Passed!\n";
            break;
        default:
            std::cout << "Unknown grade\n";
    }

    return 0;
}
3 Code Challenge
Challenge: Write a nested conditional checking if a person is old enough to vote (age 18+). If they are, check if they have registered (a boolean flag). If both are true, print "Safe to vote!". Otherwise, print the specific reason they cannot vote.