C Else
The else Statement
Use the else statement to specify a block of code
to be executed if the condition is false.
Syntax
// 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
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
bool isDay = time < 18;
if (isDay) {
printf("Good day.");
} else {
printf("Good evening.");
}
Tip: A name like isDay makes it easy to understand what the condition means.