Beginner 10 min

If-Else Statements

Learn to make decisions in your code with conditional statements and boolean logic

Learn how to make your programs intelligent by using conditional statements to make decisions based on different situations.

A Simple Example

#include <iostream>

int main() {
    int age{25};

    if (age >= 18) {
        std::cout << "You are an adult" << "\n";
    }

    // Multiple conditions with else if
    int score{85};

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

    return 0;
}

Breaking It Down

if Statement - Basic Condition

  • What it does: Executes code only when a condition is true
  • Syntax: if (condition) { code to execute }
  • Conditions use comparison operators: ==, !=, >, <, >=, <=
  • Remember: Always use == for comparison, not = which is assignment

else if - Multiple Conditions

  • What it does: Checks another condition if the previous one was false
  • Execution: Only runs if all previous conditions were false
  • Order matters: Conditions are checked top-to-bottom, first match wins
  • You can chain multiple else if statements when you need to check several different conditions

else - Default Case

  • What it does: Runs when all previous conditions are false
  • Think of it as: The "everything else" or fallback option
  • Must come last: Always appears after if and else if statements
  • Remember: else is optional - use it when you need a default action

Logical Operators - Combining Conditions

  • && (AND): Both conditions must be true - if (age >= 18 && hasLicense)
  • || (OR): At least one condition must be true - if (age < 13 || age > 65)
  • ! (NOT): Reverses the condition - if (!isStudent) means "is NOT a student"
  • Remember: Use parentheses to group complex conditions clearly

Why This Matters

  • Programs without conditionals are like robots that can only follow one path. Every meaningful program makes decisions.
  • Real software needs to respond differently based on different situations - checking user permissions, validating input, handling errors, or adapting to user choices.
  • Conditional logic is the foundation of all program control flow and decision-making.

Critical Insight

Conditions are evaluated top-to-bottom and stop at the FIRST match! This means the order of your conditions matters tremendously.

If you check score >= 60 first, a score of 100 will match that condition and never reach the "perfect score" check below it. Always order your conditions from most specific to most general.

// Wrong - score of 100 prints "Pass" and never checks for perfect
if (score >= 60) {
    std::cout << "Pass";
} else if (score == 100) {
    std::cout << "Perfect score!";  // Never reached!
}

// Correct - check most specific first
if (score == 100) {
    std::cout << "Perfect score!";
} else if (score >= 60) {
    std::cout << "Pass";
}

Best Practices

Always use braces: Even for single-line conditionals, use {} to prevent bugs when adding more code later.

Order conditions from specific to general: Check score == 100 before score >= 60.

Name complex conditions: Store bool isEligible = age >= 18 && hasLicense; then use if (isEligible).

Consider switch for discrete values: When checking many values of one variable, switch is often cleaner.

Common Mistakes

= vs ==: Writing if (x = 5) assigns 5 to x and always evaluates to true. Use == for comparison.

if (x == 5 || 6): This does not check if x is 5 or 6. The 6 is always true. Use if (x == 5 || x == 6).

Floating point comparisons: if (0.1 + 0.2 == 0.3) is false due to precision. Use a tolerance instead.

Operator precedence: && binds tighter than ||. Use parentheses: if ((a && b) || c) to be explicit.

Debug Challenge

This temperature checker has a bug. When temp is 75, nothing prints. Click the highlighted line to fix it:

1 #include <iostream>
2
3 int main() {
4 int temp{75};
5
6 if (temp > 90) {
7 std::cout << "Very hot!" << "\n";
8 } else if (temp > 90) {
9 std::cout << "Warm day" << "\n";
10 }
11
12 return 0;
13 }

Quick Quiz

  1. What does this code output if x = 10?
if (x > 15) {
    std::cout << "A";
} else if (x > 5) {
    std::cout << "B";
} else {
    std::cout << "C";
}
B
A
C
AB
  1. What is wrong with: if (score = 100)?
Nothing, it is correct
Should be `score === 100`
Should be `score == 100`
Missing semicolon
  1. Which logical operator means "AND"?
`&`
`!`
`&&`
`||`

Step Through the Code

Walk through the code step by step. Watch how variables change and see the program output at each line.

Lesson Progress

  • Fix This Code
  • Quick Quiz
  • Practice Playground - run once