CodeBlanks Logo Icon CodeBlanks

else and else if

Learn else and else if chains for alternative cases.

The else statement

To run a different block when an if condition is false you use the else statement. After the closing brace of the if block you write else and open a second block.

For example: if (age >= 18) { std::cout << "Drive"; } else { std::cout << "Wait"; }. When age is below 18 the else block runs and "Wait" is printed. else takes no condition of its own; it activates only when the if was false.

The else if chain

To separate more than two cases you use an else if chain. Each else if carries a new condition; the conditions are evaluated top to bottom and the first true condition's block runs.

For example: if (score >= 90) { ... } else if (score >= 80) { ... } else { ... }. This is ideal for cases divided into ranges such as letter grades. If no condition is true, the final else runs.

Practice Pass check

The score variable is set to 75. Use the condition if (score >= 50) to check the pass status; print "Pass" when true and "Fail" when false. Add an else block too.

Starter code

main.cpp
#include <iostream>

int main() {
    int score = 75;
    // Print the result with if and else
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int score = 75;
    if (score >= 50) {
        std::cout << "Pass" << std::endl;
    } else {
        std::cout << "Fail" << std::endl;
    }
    return 0;
}

Expected output

Pass

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the else keyword

Question
if (age >= 18) {
    std::cout << "Drive";
} ____ {
    std::cout << "Wait";
}
Answer
if (age >= 18) {
    std::cout << "Drive";
} else {
    std::cout << "Wait";
}

Explanation: else runs when the if is false.

2 Match each construct to its job

Term Meaning
if Checks the first condition
else if Adds an alternative condition
else Runs when none match
switch Multi-way constant pick

3 Which construct runs when all if and else if conditions are false?

main.cpp
// condition chain
  • if
  • else Correct answer
  • switch
  • else if

Explanation: else activates when no condition is true.

All lessons in Beginner