Else-if ladder statement in C

If there are multiple conditions of blocks, and only one is to be executed then this type of constructor is used. The general syntax for an else-if ladder is shown below.

    if(test_expression1){
        // if block1
    }
    else if(test_expression2){
        // else if block2
    }
    else if(test_expression3){
        // else if block3
    }
    else if(test_expressionn){
        // else if blockn
    }
    else{
        // default else block
    }
    statement-x;

The conditions are evaluated from top to downwards. As soon as the true condition is met, the statements associated with it are executed and the control is transferred to the statement-x(skipping the rest of the ladder). If all the test_expressions are false, then the final default else statement is executed if exists.

The block diagram/flowchart for the else-if ladder is shown below.

else-if ladder flowchart

Let’s say the user enters an integer number 1-7 and based on the number entered we have to display the day. (if 1 display Sunday, 2 display Monday) The C program is as follows.

// program to display day of week based on number
#include <stdio.h>

int main(){
    int day;
    printf("Enter an integer number:");
    scanf("%d", &day);
    if(day == 1){
        printf("Sunday");
    }
    else if(day == 2){
        printf("Monday");
    }
    else if(day == 3){
        printf("Tuesday");
    }
    else if(day == 4){
        printf("Wednesday");
    }
    else if(day == 5){
        printf("Thursday");
    }
    else if(day == 6){
        printf("Friday");
    }
    else if(day == 7){
        printf("Saturday");
    }
    else{
        printf("Number does not match.");
    }
    return 0;
}

Sample Run:

Enter an integer number:5
Thursday

In case of not matching any expression, the default case is executed. We can clearly see that the fifth test case is executed and the program flow is ended for else if ladder.