![]() |
VOOZH | about |
Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels.
Let's take a look at a simple example:
Divisible by 2 and 3
Explanation: In the above program, the outer if statement checks whether n is divisible by 2 and the inner if statement checks if n is divisible by 3. But as inner if is nested, the divisibly check with 3 is only performed if n is divisible by 2.
The nesting of if-else depends on the situation but a general syntax can be defined as:
if(condition1) {
if(condition2) {
// Statement 1
}
else {
// Statement 2
}
}
else {
if(condition3) {
// Statement 3
}
else {
// Statement 4
}
}
In the above syntax of nested if-else statements, the inner if-else statement is executed only if 'condition1' becomes true otherwise else statement will be executed and this same rule will be applicable for inner if-else statements.
The following C++ programs demonstrate the use of nested if-else statements.
10
A year is a leap year if it follows the condition, the year should be evenly divisible by 4 then the year should be evenly divisible by 100 then lastly year should evenly divisible by 400 otherwise the year is not a leap year.
2023 is not a leap year.