if statement within an if statement is called nested if statement. In nested structure, control enters into the inner if only when the outer condition is true. Only one block is executed and the remaining blocks is skipped automatically.
Syntax
The syntax of nested if is as follows :
if (condition)
if (condition){
statement(s);
}
else {
statement(s);
}
if (condition){
statement(s);
}
else {
statement(s);
}
else {
statement(s);
}
Red text is Inner if and black text is Outer if .
Working :
In nested if statement, the condition of outer if is checked. If it is true, the control enters in the inner if block. The inner if is working according to simple if statement. If the outer if condition is false, the inner if is skipped and control directly moves to the else part of outer if.
Nested if Flowchart :
Example :
#include <iostream> using namespace std; int main () { int marks = 55; if( marks >= 80) { cout << "U are 1st class !!"; } else { if( marks >= 60) { cout << "U are 2nd class !!"; } else { if( marks >= 40) { cout << "U are 3rd class !!"; } else { cout << "U are fail !!"; } } } return 0; }
Output :
U are 3rd class !!