C Nested If-Else

Nested if-else statement in C.

Nested If-Else:

A nested if-else statement is simply an if-else statement inside another if-else statement. This allows you to test multiple conditions and execute different code blocks based on the results of those conditions. Here's the basic syntax for a nested if-else statement in C:

if (condition1) {
    // Code to execute if condition1 is true
    if (condition2) {
        // Code to execute if condition2 is true
    } else {
        // Code to execute if condition2 is false
    }
} else {
    // Code to execute if condition1 is false
}

Here's a concrete example of nested if-else:

c Copy Code
#include <stdio.h>

int main() {
    int x = 10;
    int y = 5;

    if (x > y) {
        printf("x is greater than y\n");

// Nested if-else
        if (x > 15) {
            printf("x is greater than 15\n");
        } else {
            printf("x is not greater than 15\n");
        }

    } else {
        printf("x is not greater than y\n");
    }

    return 0;
}
Output:
x is greater than y 
x is not greater than 15

In this example, we have two nested if-else statements. The outer if-else checks if 'x' is greater than 'y', and depending on the result, it enters either the "if" block or the "else" block. Inside the "if" block, there's another if-else statement that checks if 'x' is greater than 15.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.