0
0
Cprogramming~5 mins

Nested conditional statements

Choose your learning style9 modes available
Introduction

Nested conditional statements help you make decisions inside other decisions. This lets your program check many things step by step.

When you want to check if a number is positive, negative, or zero, and then check if it is even or odd.
When you need to decide a grade based on score ranges and then give special messages for top scores.
When you want to check if a user is logged in, and then check their role to show different options.
When you want to check weather conditions and then decide what clothes to wear based on temperature.
Syntax
C
if (condition1) {
    if (condition2) {
        // code if both condition1 and condition2 are true
    } else {
        // code if condition1 is true but condition2 is false
    }
} else {
    // code if condition1 is false
}

You can put one if statement inside another to check more conditions.

Use braces { } to keep your code clear and avoid mistakes.

Examples
This checks if x is positive, then checks if it is even or odd.
C
if (x > 0) {
    if (x % 2 == 0) {
        printf("Positive even number\n");
    } else {
        printf("Positive odd number\n");
    }
} else {
    printf("Not a positive number\n");
}
This checks if the score is 90 or above, then if it is exactly 100.
C
if (score >= 90) {
    if (score == 100) {
        printf("Perfect score!\n");
    } else {
        printf("Great job!\n");
    }
} else {
    printf("Keep trying!\n");
}
Sample Program

This program asks the user for a number. It first checks if the number is positive, negative, or zero. If positive, it checks if it is even or odd and prints the result.

C
#include <stdio.h>

int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);

    if (number > 0) {
        if (number % 2 == 0) {
            printf("%d is a positive even number.\n", number);
        } else {
            printf("%d is a positive odd number.\n", number);
        }
    } else if (number < 0) {
        printf("%d is a negative number.\n", number);
    } else {
        printf("You entered zero.\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Always test your nested conditions with different inputs to make sure all paths work.

Too many nested conditions can make code hard to read. Keep it simple when possible.

Summary

Nested conditionals let you check one condition inside another.

Use them to make detailed decisions step by step.

Keep your code clear with braces and indentation.