Home Tutorials C Tutorial Nested if Statement
Nested if Statement

Nested if Statement


The Nested if Statement

What is a Nested if Statement?

A Nested if is simply an if statement that is placed inside the body of another if statement. This is used when you need to test multiple conditions that depend on each other.

In a nested structure, the inner if only gets evaluated if the outer if condition is True. If the first condition is False, the computer skips the entire block, including the inner code.

Syntax

if (condition1) {
    // Executes if condition1 is true
    if (condition2) {
        // Executes only if both condition1 AND condition2 are true
    }
}

Practical Examples

Example 1: Admission Eligibility

int age = 19;
int has_id = 1; // 1 means True

if (age >= 18) {
    if (has_id == 1) {
        printf("Entry Permitted.\n");
    }
}

Example 2: Finding the Greatest of Three

int a = 10, b = 20, c = 5;

if (a > b) {
    if (a > c) {
        printf("A is the greatest.\n");
    }
} else {
    if (b > c) {
        printf("B is the greatest.\n");
    }
}
Clean Code Warning: While nesting is powerful, try not to nest too deeply (more than 3 levels). If your code looks like a staircase, it becomes very hard to read! In many cases, you can use Logical Operators (&&) to simplify nested conditions.

🏋️ Test Yourself With Exercises

Take our quiz on Nested if Statement to test your knowledge.

Browse Quizzes »