This statement allows the user to use if
block inside the other if
block. And the inner if
statement is executed only if the outer if
statement’s condition is true.
The syntax of the nested if
statement in C++:
1 2 3 4 5 6 7 8 | if(condition1) { //block of code to be executed if(condition2) { //block of code to be executed } } |
You can also nest the if..else
statement in same manner as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //Nested if....else statement if(condition1) { if(condition2) { //block of statement; } else { //block of statement; } } else { //block of statement; } |
nested if statement Flowchart:
Example of nested if statement in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int a = 50; int b = 110; // check condition if (a < 100) { // agian the use of if if (b < 200) { cout << "Value of a and b are 50 and 110 respectively" << endl; } } cout << "Value of a is: " << a << endl; cout << "Value of b is: " << b << endl; return 0; } |
Output:
1 2 3 | Value of a and b are 50 and 110 respectively Value of a is: 50 Value of b is: 110 |
Example of C++ nested if…else statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> using namespace std; int main() { int a, b, c; cout << "Enter 3 integers: "; cin >> a >> b >> c; if (a > b) { if (a > c) { cout << a << " is greatest of all."; } else { cout << c << " is greatest of all."; } } else { if (b > c) { cout << b << " is greatest of all."; } else { cout << c << " is greatest of all."; } } } |
Output:
1 2 | Enter 3 integers: 2 5 4 5 is greatest of all. |