In the previous post (Decision Using IF and ELSE), is explained about decision, but only for 2 conditions.
What if there are more then 2 conditions.
The format of the syntax is not different; just add one or more syntax; it is else if.
This format below is for 4 conditions:
if (condition 1)
{statement 1}
else if (condition 2)
{Statement 2}
else if (condition 3)
{Statement 3}
else
{Statement 4}
Let’s try this case.
We want the program to show whether the number inserted is a positive number or negative number or zero number.
In this case, we need one if, one else if, and one else.
Just see the example below:
#include "iostream.h"
#include "conio.h"
main()
{
int x;
cout<<"Insert a number: ";
cin>>x;
if (x>0)
{cout<<"Positive Number";}
else if (x<0)
{cout<<"Negative Number";}
else
{cout<<"Zero Number";}
getch();
}
The result will be like this:
1. if we insert a number more than 0, the program will print Positive Number, because the condition is TRUE on if syntax line.
2. if we insert a number less than 0, the program will print Negative Number, because the condition is FALSE on if syntax line, but TRUE on else if syntax line.
3. if we insert a number 0, the program will print Zero Number, because the condition is not TRUE on all the condition declared on if syntax line, and all else if syntax line, above else syntax line.
So the exception of all conditions will goes to else syntax line, and the statement on it will be run.
0 comments:
Post a Comment