A girl and a robot thinking together

Let’s think it through · Start with a story

The robot gives stickers based on scores: gold for 90 or above, blue for 60 or above, and green otherwise. Which sticker should a score of 95 get?

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Check 90 first95 qualifies
  2. Choose goldRun this branch
  3. Skip later branchesDo not check for blue

if / else if / else checks conditions in order and runs the first branch whose condition is true.

Conditions can overlap, so order matters. A score of 95 is both at least 60 and at least 90, but the gold rule should come first.

01What if there are three or four cases?

For example, you can assign letter grades by score:

if (score >= 90) {
    std::cout << "A";
} else if (score >= 80) {
    std::cout << "B";
} else if (score >= 60) {
    std::cout << "C";
} else {
    std::cout << "D";
}

02How does else if choose a branch?

The program checks from top to bottom. When it finds the first true condition, it runs that branch and skips the remaining branches in the same chain.

Check ≥ 90 first↓Then check ≥ 80↓Choose the first true condition

03Why does order matter?

// Incorrect order
if (score >= 60) {
    std::cout << "C";
} else if (score >= 90) {
    std::cout << "A";
}

If score = 95, the first condition, score >= 60, is already true, so the later >= 90 condition is never checked.

04When should you use &&?

Use it when a branch requires several conditions to be true at the same time:

if (age >= 10 && registered) {
    std::cout << "You may participate";
}

Both conditions must be true here.

05When should you use ||?

Use it when any one of the conditions is enough:

if (isWeekend || isHoliday) {
    std::cout << "Time off";
}

06When should you use separate if statements versus else if?

Several separate if statements

Use them when multiple conditions may be true and each should be handled.

An if / else if chain

Often used when cases are mutually exclusive and only one branch should be chosen.

What you have learned

  • else if creates a chain with multiple branches.
  • The program checks from top to bottom and chooses the first true branch.
  • The order of conditions directly affects the result.
  • &&, ||, and ! can be used to combine conditions.
  • Separate if statements and an else-if chain have different meanings.

Next: for: Make the Computer Repeat Something

Your turn

If you put the condition for 60 before the one for 90, what will happen to a score of 95?

Have an answer? Click to see the explanation

It enters the first matching branch—the one for 60—and gets blue. Put conditions in an order that matches the rules, or write the ranges explicitly.