The else Branch
The if statement runs its block only if the condition is true. Often, though, you want to do something when it isn't true, too. That's what else is for:
int temperature = 12;
if (temperature > 25) {
printf("Take a cap\n");
} else {
printf("Take a jacket\n");
}This prints:
Take a jacketThe condition temperature > 25 is false, so the program skips the first block and runs the block after else. These two blocks are called branches: like a road that forks, the program always takes exactly one of them. If the condition is true, the first branch, otherwise the second. It never runs both, and it never skips both.
You write else right after the closing brace of the if block, usually on the same line: } else {. There must be no other statement between the } and the else. Otherwise the else has nothing to belong to, and the compiler reports error: expected expression.
else has no condition of its own: it gets all the cases the if didn't cover. If you give it one anyway, for example } else (temperature <= 25) {, the compiler reports error: expected ';' after expression. The error suggests adding a semicolon, but the right fix is to delete the condition after else.
Instructions
The monitor now costs 5000, so the program prints nothing. Add an else branch to the if statement that prints I won't buy the monitor.
Change monitor_price to 3500 and run the program again. Now the condition is true, so the program takes the first branch and prints only I'll buy the monitor.
Start programming for free
3/12