Exploring the C Else Statement: Conditional Code Execution
Understand the purpose of the else statement in C programming, which allows for conditional code execution when an if statement evaluates to false. Learn how to effectively implement else statements in your programs for improved logic flow.
C Else Statement
The else Statement
The else statement is used to specify a block of code to be executed if the condition in the if statement evaluates to false.
Syntax
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
}
Example
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
Output
Good evening.
Example Explained
In the example above, the value of time is 20, which is greater than 18. This makes the condition in the if statement false, so the program moves to the else block and prints "Good evening."
If the value of time had been less than 18, the program would have printed "Good day."