• Home
• Nested if….else statement in C

# Nested if….else statement in C

A nested if…else statement is an if…else statement that is contained within another if…else statement. The syntax for a nested if…else statement is as follows:

``````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
}``````

For example, consider the following code:

``````int x = 10;
int y = 20;
if (x > 5) {
if (y > 15) {
printf("x is greater than 5 and y is greater than 15\n");
} else {
printf("x is greater than 5 but y is not greater than 15\n");
}
} else {
printf("x is not greater than 5\n");
}``````

In this example, the outer if statement checks the condition (x > 5), which is true because the value of x (10) is greater than 5. The inner if statement then checks the condition (y > 15), which is also true because the value of y (20) is greater than 15. Therefore, the message “x is greater than 5 and y is greater than 15” is printed to the console.

It is important to note that the inner if…else statement is only executed if the outer if statement’s condition is true. If the outer if statement’s condition is false, the inner if…else statement is skipped and the code inside the else block of the outer if statement is executed.

For example:

``````int x = 4;
int y = 20;
if (x > 5) {
if (y > 15) {
printf("x is greater than 5 and y is greater than 15\n");
} else {
printf("x is greater than 5 but y is not greater than 15\n");
}
} else {
printf("x is not greater than 5\n");
}``````

In this example, the outer if statement’s condition (x > 5) is false, so the code inside the outer if block is not executed. Instead, the code inside the else block of the outer if statement is executed and the message “x is not greater than 5” is printed to the console.