else-if Statement

The else-if statement allows multiple conditions to be checked sequentially. The compiler first checks the if statement. If the condition in the if statement is true, the code inside the if block will execute. If the condition in the if statement is false, the compiler moves on to the else-if statement. The compiler checks the condition in the else-if statement, and if it is true, the code inside the else-if block will execute. If both the if and else-if conditions are false, the code inside the else block will execute.

Syntax


if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else if (condition3) {
    // Code to execute if condition3 is true
} else {
    // Code to execute if none of the above conditions are true
}
                    
                

Here is an example of how the else-if statement works:

Example 1 : Check if given number is zero, positive or negative


#include <stdio.h>
int main() {
    int number = 0;
    if (number > 0) {
        printf("The number is positive.\n");
    } else if (number < 0) {
        printf("The number is negative.\n");
    } else {
        printf("The number is zero.\n");
    }
    return 0;
}

Output

The number is zero.

Example 2 : Classify a person based on their age.


#include <stdio.h>
int main() {
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);
    if (age < 13) {
        printf("You are a child.\n");
    } else if (age >= 13 && age < 20) {
        printf("You are a teenager.\n");
    } else if (age >= 20 && age < 60) {
        printf("You are an adult.\n");
    } else {
        printf("You are a senior citizen.\n");
    }
    return 0;
}

Output

Enter your age: 25 You are an adult.

Key points

  1. Efficiency:
    • The program stops checking conditions as soon as one is true.
    • Arrange conditions from most likely to least likely for better performance.
  2. Chaining:
    • You can chain multiple else if statements as needed.
    • Avoid overusing them to keep the code readable.
  3. Default Handling:
    • Use the final else block to catch any unexpected cases.
  4. Alternative:
    • In some cases, switch statements can be used instead of if-else if, especially when testing a single variable against multiple values.