0
0
CHow-ToBeginner · 3 min read

How to Use Nested If Else in C: Simple Guide with Examples

In C, you use nested if else by placing an if else statement inside another if or else block. This allows you to check multiple conditions step-by-step, making decisions more detailed and specific.
📐

Syntax

The nested if else structure means putting one if else inside another. The outer if checks the first condition, and inside its block, you can add another if else to check a second condition.

Here is the basic pattern:

  • if (condition1): Checks the first condition.
  • {: Starts the block for the first condition.
  • if (condition2): Checks the second condition inside the first.
  • else: Runs if the second condition is false.
  • }: Ends the block for the first condition.
  • else: Runs if the first condition is false.
c
if (condition1) {
    if (condition2) {
        // code if both conditions are true
    } else {
        // code if condition1 is true but condition2 is false
    }
} else {
    // code if condition1 is false
}
💻

Example

This example shows how to check a number and print messages based on whether it is positive, negative, or zero, using nested if else statements.

c
#include <stdio.h>

int main() {
    int num = 10;

    if (num != 0) {
        if (num > 0) {
            printf("The number is positive.\n");
        } else {
            printf("The number is negative.\n");
        }
    } else {
        printf("The number is zero.\n");
    }

    return 0;
}
Output
The number is positive.
⚠️

Common Pitfalls

One common mistake is forgetting to use braces { } for nested blocks, which can cause only the next line to be part of the if or else. This leads to unexpected behavior.

Another pitfall is confusing which else belongs to which if. Always use braces to clearly group your conditions.

c
/* Wrong way without braces */
if (num > 0)
    if (num < 100)
        printf("Number is positive and less than 100\n");
    else
        printf("Number is not positive\n");

/* Right way with braces */
if (num > 0) {
    if (num < 100) {
        printf("Number is positive and less than 100\n");
    }
} else {
    printf("Number is not positive\n");
}
📊

Quick Reference

  • Always use braces { } to avoid confusion.
  • Indent nested blocks for better readability.
  • Each else matches the closest previous unmatched if.
  • Nested if else helps check multiple conditions stepwise.

Key Takeaways

Use nested if else to check multiple conditions inside each other.
Always use braces to clearly group nested blocks and avoid errors.
Indent your code to make nested conditions easy to read.
Remember each else pairs with the nearest if without an else.
Nested if else helps make decisions more detailed and specific.