Lesson 51 +10 XP

else if Statements

else if Statements

Sometimes you need more than two outcomes. That's what else if is for.

The ladder

int time = 22;
if (time < 10) {
    printf("Good morning.");
} else if (time < 20) {
    printf("Good day.");
} else {
    printf("Good evening.");
}

Output: Good evening.

How it works

  • Check time < 10 first. If true, stop.
  • Otherwise check time < 20. If true, stop.
  • Otherwise run the final else.

Order matters

The conditions are tested top to bottom, and the first true one wins. Put the most specific conditions first.

TL;DR

  • else if chains extra conditions after an if.
  • The first true condition wins.
  • A final else catches everything else.
  • Conditions run top to bottom.