Sunday, January 17, 2010

Nested IF

Some time we need to make a decision in a decision.
For example we use a decision IF, and we put a decision IF again inside it.
We can call this system as Nested IF.

Let’s see this case.
We want to make a program to decide which number are the highest among the three numbers we entered.
In the previous post ( Simple program using logical operator), we have a program to decide the middle number.
Just like that program, do this step.
First step, make the program to ask the user to enter three numbers one by one, by cin>> syntax.
Then make the main program, but it is a little bit different with the program we have in the previous post at IF decision.
Here we use a nested IF.

See the complete syntax below:

#include "iostream.h"
#include "conio.h"
main()
{
int a, b, c, x;
cout<<"The Highest Number";
cout<<"\n==================";

cout<<"\n\nEnter first number: ";cin>>a;
cout<<"Enter second number: ";cin>>b;
cout<<"Enter third number: ";cin>>c;

if(a>b)
{
if(a>c)
{cout<<"The highest number is: ";
cout<< a;}
else
{cout<<"The highest number is: ";
cout<< c;}
}
else if (b>c)
{
if(b>a)
{cout<< "The highest number is: ";
cout<< b;}
else
{cout<< "The highest number is: ";
cout<< a;}
}
else if(c>a)
{
if(c>b)
{cout<< "The highest number is: ";
cout<< c;}
else
{cout<< "The highest number is: ";
cout<< b;}
}
else
{cout<< "The three numbers are the same.";}
getch();

}

See the picture below as the result of the program we made above.






0 comments:

Post a Comment