C nested if Statement

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
Layered logic

What You’ll Learn

A nested if places one condition inside another. The inner test runs only when the outer test already passed—perfect for step-by-step checks like “is the user an adult?” then “did they pass the exam?” This tutorial builds on if, if-else, and else if with clear syntax, five examples, and tips to keep nested code readable.

01

Inside if

Layer tests.

02

Order

Outer first.

03

Braces

Always { }.

04

&&

Flatten simple.

05

else if

Flat ladder.

06

Indent

Read depth.

Definition and Usage

A nested if statement is an if written inside the body of another if or else block. The inner condition is evaluated only when the outer condition is true (or when execution enters that else branch).

Use nesting when a second decision depends on the first. Admission checks, login validation, and “positive then even/odd” splits are classic patterns. When several outcomes sit at the same level, an else if ladder is often clearer.

💡
Beginner Tip

Indent each nested level consistently. If the code drifts far to the right, consider combining conditions with && or refactoring into a separate function.

📝 Syntax

General form of a nested if inside an outer if:

C
if (outer_condition) {
    // outer body runs when outer_condition is true
    if (inner_condition) {
        // runs only when BOTH outer and inner are true
    }
}

Nested if-else

You can nest if-else inside if or else blocks:

C
if (condition1) {
    if (condition2) {
        // both true
    } else {
        // condition1 true, condition2 false
    }
} else {
    // condition1 false
}

Evaluation order

  • Outer if — tested first.
  • Inner if — tested only if the outer block is entered and its condition was true.
  • Both must pass — for the innermost body to run when using nested if without else between them.
  • Braces — use { } on every branch to avoid dangling else bugs.

Compile

C
gcc program.c -std=c11 -o program

⚡ Quick Reference

PatternExample
Two-level checkif (a) { if (b) { ... } }
Flatten with &&if (a && b) { ... }
Outer elseif (a) { if (b) ... } else { ... }
Inner elseif (a) { if (b) ... else ... }
Prefer else ifSame-level grades A/B/C → else if
Depends
inner after outer

Layered logic

Braces
always { }

Safe nesting

&&
both true

Simpler form

Depth
2-3 max

Readability

Examples Gallery

Compile with gcc example.c -std=c11 -o example. Each program shows a different nested if pattern.

📚 Getting Started

Basic nesting and dependent conditions from the reference material.

Example 1 — Positive and Even

Outer if checks sign; inner if checks parity.

C
#include <stdio.h>

int main(void) {
    int num = 10;

    if (num > 0) {
        printf("Number is positive\n");

        if (num % 2 == 0) {
            printf("Number is even\n");
        }
    }

    return 0;
}

How It Works

10 > 0 is true, so the outer block runs. Inside it, 10 % 2 == 0 is also true, so “even” prints. A negative number would skip the entire outer block.

Example 2 — Admission Eligibility

Check age first; only then evaluate grade.

C
#include <stdio.h>

int main(void) {
    int age = 20;
    int grade = 85;

    if (age >= 18) {
        if (grade >= 60) {
            printf("Eligible for admission\n");
        } else {
            printf("Not eligible due to low grade\n");
        }
    } else {
        printf("Not eligible due to age\n");
    }

    return 0;
}

How It Works

Grade is checked only when age passes. A 16-year-old with a high grade still fails at the outer else—the inner block never runs.

📈 Practical Patterns

Nested if-else, flattening, and real-world guards.

Example 3 — Zero, Positive, or Negative

Outer split on sign; inner if-else separates zero from positive.

C
#include <stdio.h>

int main(void) {
    int number = -5;

    if (number >= 0) {
        if (number == 0) {
            printf("Number is zero\n");
        } else {
            printf("Number is positive\n");
        }
    } else {
        printf("Number is negative\n");
    }

    return 0;
}

How It Works

-5 >= 0 is false, so the outer else runs immediately. For a flat three-way split without dependency, see else if.

Example 4 — Flatten with Logical &&

When both conditions must be true with no middle else, combine them.

C
#include <stdio.h>

int main(void) {
    int num = 10;

    if (num > 0 && num % 2 == 0) {
        printf("Number is positive and even\n");
    }

    return 0;
}

How It Works

This replaces Example 1’s nested if when you only need one combined message. C evaluates && left to right and skips the right side if the left is false.

Example 5 — Bank Withdrawal Guard

First confirm funds exist; then verify the amount is within balance.

C
#include <stdio.h>

int main(void) {
    double balance = 500.0;
    double amount = 200.0;

    if (balance > 0) {
        if (amount <= balance) {
            balance -= amount;
            printf("Withdrawal OK. New balance: %.2f\n", balance);
        } else {
            printf("Insufficient funds for %.2f\n", amount);
        }
    } else {
        printf("Account has no funds\n");
    }

    return 0;
}

How It Works

The amount check only matters when the account has a positive balance. Each else gives a specific rejection reason—a pattern you will see in validation code everywhere.

🚀 Common Use Cases

  • Eligibility — age, then score, then documents verified.
  • Authentication — user found, then password matches.
  • Input validation — in range, then format correct.
  • Classification — positive, then even/odd or divisible by N.
  • Resource guards — file open, then read succeeds.
  • Business rules — discount applies, then cart total qualifies.

🧠 How Nested if Works

1

Test outer if

Evaluate the first condition.

Start
2

Enter block?

If false, skip inner tests and jump to outer else if any.

Gate
3

Test inner if

Only now is the nested condition evaluated.

Layer
=

Run or skip inner body

Both true → inner body. Otherwise inner else or continue after nesting.

📝 Notes

  • Indent each nesting level so structure is visible at a glance.
  • Always use braces—they prevent dangling else mistakes.
  • Two simple AND conditions can often be one line with &&.
  • Same-level exclusive outcomes belong in an else if ladder, not deep nesting.
  • Extract logic into functions when nesting exceeds two or three levels.
  • Comments on non-obvious branches help future readers (including you).

⚡ Optimization

Put the cheapest or most likely-to-fail outer condition first so inner tests are skipped when possible. Combining independent checks with && lets the compiler short-circuit: if the left side is false, the right side is not evaluated. For very deep trees, a switch or lookup table may outperform a long nested chain—but clarity matters more than micro-optimization at beginner scale.

Conclusion

Nested if statements let C programs make layered decisions—each inner test builds on the outer one. Use them when the second condition only makes sense after the first passes; flatten with && or else if when nesting adds no real structure.

Brace every branch, indent consistently, and keep depth shallow. Next up: the switch statement for many equal comparisons on one value.

💡 Best Practices

✅ Do

  • Use braces on every if and else
  • Indent nested blocks consistently (2 or 4 spaces)
  • Put the broad outer guard first (age, login, balance)
  • Flatten independent AND checks with &&
  • Refactor deep trees into functions or else if

❌ Don’t

  • Nest four or more levels without refactoring
  • Omit braces—dangling else risk
  • Use nesting when an else if ladder is clearer
  • Duplicate the same inner block in multiple outer branches
  • Forget that inner code never runs if outer fails

Key Takeaways

Knowledge Unlocked

Five things to remember about nested if

Layered decisions in C.

5
Core concepts
02

Outer first

Gate inner.

Flow
🔢 03

Braces

Always { }.

Safety
📝 04

&&

Flatten.

Simplify
🔌 05

else if

Flat alt.

Menus

❓ Frequently Asked Questions

A nested if is an if statement placed inside another if (or else) block. The inner if runs only when the outer condition is already true. This lets you test layered requirements step by step.
C does not set a hard limit, but deep nesting (four or more levels) is hard to read and maintain. Prefer else if ladders, logical operators (&&, ||), or small helper functions when logic grows.
Use nested if when a second condition only matters after the first is true—e.g. check age, then check grade. Use else if when outcomes are mutually exclusive at the same level—e.g. A, B, C grade bands.
When both conditions must be true together and there is no else branch between them, combine with &&: if (a > 0 && a % 2 == 0). This is clearer than two nested ifs with no else in between.
Always use { } on every if and else in real code. Braces make nesting visible, prevent the dangling-else ambiguity, and stop bugs when you add another line later.
In C, else binds to the nearest unmatched if. Without braces, else may attach to the wrong if in nested code. Always brace nested blocks so else clearly belongs to the if you intend.
Did you know?

In C, else always pairs with the nearest preceding if that does not already have an else. In nested code without braces, a misplaced else can bind to the wrong if—the classic “dangling else” problem. Braces make the pairing unambiguous.

Continue to switch

Learn how switch handles many constant comparisons on a single expression.

switch tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful