These statements are used to control the flow of execution of a program by making a decision depending on a condition, hence they are named as decision making statements. Decision making statements are of four types.
- Simple if
- if else
- nested if else
- If else ladder
1. Simple if Statement
if the test expression is true then if statement executes statements that immediately follow if
Syntax:
If(test expression)
{
List of statements;
}
Example:
#include<stdio.h>
int main()
{
int a,b;
cout<<“Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
if(b>a)
cout<<“B is larger than A\n A=”<<b;
return 0;
}
2. if-else Statement
If test expression is true block of statements following if are executed and if test expression is false then statements in else block are executed.
Syntax:
if (test expression)
{
statement block1;
}
else
{
statement block2;
}
Example:
/*largest of two numbers*/
#include<iostream.h>
int main()
{
int a,b;
cout<<”Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
else
cout<<“B is larger than A\n A=”<<b;
return 0;
}
3. Nesting of if-else statements
It’s also possible to nest one if statement inside another. When a series of decisions are to be made. Simply If –else statement placed inside another if else statement.
Syntax:
If(test expression)
{
If(test expression) {
//statements
}
else
{
//statements
}
}
else
{
If(test expression) {
//statements
}
else {
//statements
}
}
Example:
/*largest of three numbers*/
#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c;
cout<<"Enter a,b,c values:";
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
{
cout<<"A ia largest among three numbers\n";
cout"A= "<<a;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"c= "<<c;
}
}
else
{
if(b>c)
{
cout<<"B ia largest among three numbers\n";
cout<<"B="<<b;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"c="<<c;
}
}
getch();
return 0;
}
4. if else ladder
The nesting of if-else depends upon the conditions with which we have to deal. The condition is evaluated from top to bottom.if a condition is true the statement associated with it is executed. When all the conditions become false then final else part containing default statements will be executed.
Syntax:
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
Example:
#include<iostream.h>
void main()
{
int per;
cout<<”Enter percentage”;
cin>>per;
if(per>=80)
cout<<”Secured Distinction”<<endl;
else if(per>=60)
cout<<”Secured First Division”<<endl;
else if(per>=50)
cout<<”Secured Second Division”<<endl;
else if(per>=40)
cout<<”Secured Third Division”<<endl;
else
cout<<”Fail”<<endl
}
You must log in to post a comment.