If else Ladder Statement in C Programming

The if else ladder statement in C programming language is used to test set of conditions in sequence. An if condition is tested only when all previous if conditions in if-else ladder is false. If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.

Syntax of if else ladder statement

if(condition_expression_One) {
    statement1;
} else if (condition_expression_Two) {
    statement2;
} else if (condition_expression_Three) {
    statement3;
} else {
    statement4;
}
  • First of all condition_expression_One is tested and if it is true then statement1 will be executed and control comes out out of whole if else ladder.
  • If condition_expression_One is false then only condition_expression_Two is tested. Control will keep on flowing downward, If none of the conditional expression is true.
  • The last else is the default block of code which will gets executed if none of the conditional expression is true.

C-If-Else-Ladder-Statement

C Program to print grade of a student using If Else Ladder Statement

If else Ladder Statement in C Programming

#include<stdio.h>
#include<conio.h>
 
int main(){
    int marks;
     
    printf("Enter your marks between 0-100\n");
    scanf("%d", &marks);
    /* Using if else ladder statement to print
       Grade of a Student */
    if(marks >= 90){
        /* Marks between 90-100 */
        printf("YOUR GRADE : A\n");
    } else if (marks >= 70 && marks < 90){
        /* Marks between 70-89 */
        printf("YOUR GRADE : B\n");
    } else if (marks >= 50 && marks < 70){
        /* Marks between 50-69 */
        printf("YOUR GRADE : C\n");
    } else {
        /* Marks less than 50 */
        printf("YOUR GRADE : Failed\n");
    }
       
    getch();
    return(0);
}

Above program check whether a student passed or failed in examination using if statement.

Output

Enter your marks
96
YOUR GRADE : A
Enter your marks
75
YOUR GRADE : B
Enter your marks
60
YOUR GRADE : C
Enter your marks
35
YOUR GRADE : Failed

Points to Remember about If else ladder statement

  • The condition_expression is a boolean expression. It must evaluate to true or false value(In C, all non-zero and non-null values are considered as true and zero and null value is considered as false).
  • We may use more than one condition inside if else ladder statement
    For Example:
    if(condition_one && condition_two) {
    /* if code block */
    } else if(condition_three) {
    /* else code block */
    }
  • Default else block is optional in if-else ladder statement.
  • Opening and Closing Braces are optional, If the block of code of if else statement contains only one statement.
    For Example:
    if(condition_expression)
    statement1;
    else if(condition_expression)
    statement2;
    In above example only statement1 will gets executed if condition_expression is true.