Understanding the C Else If Statement: Conditional Logic in Programming

Learn about the else if statement in C programming, which enables the testing of multiple conditions in a clear and organized manner. Discover how to effectively use else if to enhance your program's decision-making process.



C Else If Statement

The else if Statement

The else if statement allows you to specify a new condition to test if the first condition in an if statement is false.

Syntax

Syntax

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if condition1 is false and condition2 is true
} else {
  // block of code to be executed if both condition1 and condition2 are false
}

Example: Using else if to Compare Time

In the following example, we use an else if statement to check multiple conditions based on the time of day:

Example

int time = 22;
if (time < 10) {
    printf("Good morning.");
} else if (time < 20) {
    printf("Good day.");
} else {
    printf("Good evening.");
}
Output

Good evening.

Example Explained

In this example, the value of time is 22. The program first checks if time < 10, which is false. Then it moves to the else if statement to check if time < 20, which is also false. Since both conditions are false, the program executes the block inside the else statement, printing "Good evening."

If the value of time had been 14, the program would have printed "Good day" instead.