Lesson 50 +10 XP

else Statements

else Statements

if decides what to do when something is true. else handles the "everything else" case.

if ... else

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

Output: Good evening.

Since 20 < 18 is false, the else block runs instead.

The pattern

if (condition) {
    // runs when true
} else {
    // runs when false
}

Exactly one of the two blocks always runs.

Real-life example

int temperature = 15;
if (temperature > 20) {
    printf("It's warm!");
} else {
    printf("Bring a jacket.");
}

TL;DR

  • else runs when the if condition is false.
  • One of the two blocks always executes.
  • Use it for the "otherwise" path of a decision.