Nested if statement in C++
In nested if statement, one if statement block is enclosed within another if statement block. The syntax of nested if statement is: if(Test-Condition-1) { if(Test-Condition-2) Statement-Block-1; else Statement-Block-2; } else { if(Test-Condition-3) Statement-Block-3; else Statement-Block-4; }
Test-Condition-1, Test-Condition-2 and Test-Condition-3 are conditions
Initially Test-Condition-1 condition is evaluated. If it is true, Test-Condition-2 condition is evaluated. If Test-Condition-2 is also true, Statement-Block-1 of statements gets executed. If Test-Condition-2 condition is false, Statement-Block-2 of statements is executed. If Test-Condition-1 condition is false, Test-Condition-3 condition is evaluated. If it is true, Statement-Block-3 of statements gets executed. if Test-Condition-3 is false, Statement-Block-4 of statements gets executed.
Program to demonstrate the use of nested if statement in C++. |
#include<iostream> using namespace std; int main() { int n; cout<<“\nEnter a value="; cin>>n; if(n>=0) { if(n<=10) cout<<“Value lies between 0 and 10"; else cout<<“Value is larger than 10"; } else cout<<“Value is smaller than 0"; return(0); } |
Output |
Enter a value:=11
Value is larger than 10
|
In the above program, value of variable n has been entered 3.
Test condition if(n>=0) is true, So condition if(n<=10) is also checked. This condition is also true so statement cout<<“Value lies between 0 and 10″; gets executed.