Utilize the else if statement to designate a new condition to evaluate if the initial condition is false.
if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false } |
int time = 22; if (time < 10) { printf(“Good morning.”); } else if (time < 20) { printf(“Good day.”); } else { printf(“Good evening.”); } // Outputs “Good evening.” |
In the provided example, since the time (22) exceeds 10, the first condition is false. Subsequently, the subsequent condition in the else if statement is also false. Hence, the program proceeds to the else condition, as both condition1 and condition2 are false, and outputs “Good evening” to the screen.
Yet, if the time were 14, our program would output “Good day.”