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
Write a C program to check whether a number is even or odd
Write a C program to check whether a user is eligible to vote or not
Write a C program to check whether an alphabet is vowel or consonant
Write a C program to find the maximum number between three numbers
Write a C program to check whether a number is positive, negative or zero
Write a C program to calculate an electricity bill
Write a C program to print 1 to 10 numbers using a while loop
Interview Questions & Answers
What is the difference between while and do while loop in C?
What is the difference between break and continue in C?
How to check if a number is prime in C?
How to find the factorial of a number in C?