The nested if-else statement is used when a program requires more than one test expression.
We can write if-else statements within another if statement or in the body of else, this is called nested if-else. Nested if-else is a decision making statement.
Syntax of nested if-else statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
if (condition1) { statement 1; } else if (condition2) { statement 2; } else if (condition3) { statement 3; } else { statement 4; } |
How nested if-else works?
The nested if-else statement has more than one test expression. First of all, if the condition1 is true, it executes the code inside the braces {} just below it. But if the condition1 is false, it checks the respected else-if block i.e. condition2. If the condition2 is true, it executes the code inside the braces {} just below it. This process continues. In this way nested if-else work.
Flowchart of nested if-else statement:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<stdio.h> int main() { int number = 55; if (number == 0) { printf("number is 0"); } else if (number < 0) { printf("number is negative"); } else if (number > 0) { printf("number is positive"); } } |
Output:
1 |
number is positive |
Forms of nested if –
Following all forms of if, if-else, nested if-else, nested if are valid.
The if statement can be any of the following:
-
1if(condition) { }
-
12if(condition) { }else { }
-
12if(condition) { }else if(condition) { }
-
123456if(condition) { }else{if(condition) { }else { }}
-
1234567if(condition){if(condition) { }else { }}else{ }
-
1234if(condition) { }else if(condition)else if(condition) { }else { }
-
1234if(condition) { }if(condition) { }if(condition) { }else { }
-
1234if(condition) { }else if(condition){ }if(condition) { }if(condition) { }