Thursday, 5 March 2015

Nested if statement in C++programming

Nested if statement In nested if statement the outer if statement is executed first if the outer loop condition is true then t... thumbnail 1 summary

Nested if statement



In nested if statement the outer if statement is executed first if the outer loop condition is true then the next inner statement condition will be checked and if the inner loop is true then it will executed. and then next and so on.
Syntax
 
if (condition1)
{
if(condition 2)
{
Statement of condition 2
}
Statement of condition 1
}


Example 1 
In this example the outer loop condition is false and the inner loop condition is true but it will not executed and no result will display.
#include<iostream.h>
int main()
{
int a=3;
int b=8;
int c=8;
int d=5;
if(a>b)
{
if(c>d)
{cout<<"Display result when c>d"<<endl;
}
cout<<"Display result when a>b "<<endl;
}
system("pause");
return 0;
};
In this example the out loop condition is false and the inner loop condition is true but it will not execute and no result will display screen.

Example 2 
In this example the outer loop condition is true and the inner loop condition is false so it will display the result which is related to the outer statement and output result will display.
#include<iostream.h>
int main()
{
int a=8;
int b=6;
int c=8;
int d=11;
if(a>b)
{
if(c>d)
{
cout<<"Display result when c>d"<<endl;
}
cout<<"Display result when a>b "<<endl;
}
system("pause");
return 0;
};
Output :
Display result when a>b.



Example 3 
If both of two conditions are true then both of statement will be executed for example.
#include<iostream.h>
int main()
{
int a=8;
int b=6;
int c=5;
int d=2;
if(a>b)
{
if(c>d)
{
cout<<"Display result when c>d"<<endl;
}
cout<<"Display result when a>b "<<endl;
}
system("pause");
return 0;
};
Output : Both of the statement will print on the screen.