The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
In the example below, the program checks the value of time. If it is less than 18, it prints "Good day". Otherwise, it prints "Good evening":
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If time was less than 18, the program would print "Good day".
Using a Boolean Variable
You can also store the condition in a boolean variable and use it in the if...else statement. This can make the code easier to read:
Example
int time = 20;
bool isDay = time < 18;
if (isDay) {
printf("Good day.");
} else {
printf("Good evening.");
}
Tip: A name like
isDaymakes it easy to understand what the condition means.