C Else If Ladder and Nested If

When there are more than two choices, we use the else if ladder. The conditions are checked from top to bottom. The first true one runs, and the rest are skipped.

Else if ladder

#include <stdio.h>

int main(void) {
    int marks = 72;

    if (marks >= 90) {
        printf("Grade A\n");
    } else if (marks >= 75) {
        printf("Grade B\n");
    } else if (marks >= 50) {
        printf("Grade C\n");
    } else {
        printf("Fail\n");
    }
    return 0;
}

Output:

Output of the above program is

Grade C

Here 72 is not 90 or more, and not 75 or more, but it is 50 or more. So Grade C is printed.

Nested if

An if inside another if is called a nested if. The inner one is checked only when the outer condition is true.

#include <stdio.h>

int main(void) {
    int age = 25;
    int hasLicense = 1;

    if (age >= 18) {
        if (hasLicense) {
            printf("You can drive.\n");
        } else {
            printf("Get a license first.\n");
        }
    } else {
        printf("You are too young.\n");
    }
    return 0;
}

Output:

Output of the above program is

You can drive.

Largest of three numbers

#include <stdio.h>

int main(void) {
    int a = 12, b = 45, c = 30;

    if (a >= b && a >= c) {
        printf("%d is largest\n", a);
    } else if (b >= a && b >= c) {
        printf("%d is largest\n", b);
    } else {
        printf("%d is largest\n", c);
    }
    return 0;
}

Output:

Output of the above program is

45 is largest

Note: Put the most common or the most strict condition first. Too many nested levels are hard to read, so use && or a ladder when possible.

Next: C Switch Statement.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.