Selection Structure
The ‘if’ Statement:
The ‘if’ statement is a simple selection statement. It is decision making statement. It is used to execute or skip a statement or a set of statement after testing a condition.
Syntax
If(condition)
{
Statement-1;
Statement-1;
Statement-2;
……….…
Statement-m;
}
}
Statement-n;
Example
#include<iostream>
using namespace std;
int main( )
{
int a,b;
int a,b;
cout<<"Enter First Number =";
cin>>a;
cout<<"Enter second Number =";
cin>>b;
if(a>b)
cout<<”A is greater” <<a;
if(a<b)
cout<<”B is greater”<<b;
return 0;
}
}
The ‘if else’ Statement:
The ‘if else’ statement is another form of ‘if’ statement. It is used to making two way decision. In ‘if else’ statement one condition and two block of statement givens. It is execute first block if condition is true otherwise next block execute.
Syntax
if(condition)
{
Block-1
Block-1
}
else
{
Block-2
}
Example
#include<iostream>
using namespace std;
int main( )
{
int a,b;
cout<<"Enter First Number =";
cin>>a;
cout<<"Enter second Number =";
cin>>b;
if(a>b)
cout<<”A is greater” <<a;
else
cout<<”B is greater”<<b;
return 0;
}
The nested ‘if’ Statement:
An ‘if’ statement within another ‘if’ statement is called nested ‘if’ statement. The ‘if’ statement contain another ‘if’ statement is called outer ‘if’ statement and the statement used inside called inner ‘if’ statement.
Syntax
if(condition-1)
{
if(condition-2)
{
Block-1;
}
else
{
Block-2;
}
else
{
Block-3;
}
Example
#include<iostream>
using namespace std;
int main( )
{
int a,b,c;
cout<<"Enter First Number =";
cin>>a;
cout<<"Enter second Number =";
cin>>b;
cout<<"Enter third Number =";
cin>>c;
if(a>b)
{
if(a>b)
cout<<”A is greater” <<a;
else
cout<<”B is greater”<<b;
}
else
cout<<”C is greater”<<c
return 0;
}
The Switch Statement:
The ‘switch’ statement is another selection structure. It can be used alternative of ‘if else if’ statement. It is used when multiple choice are given and one choice is selected.
Syntax
switch(expression)
{
case 1:
Statement-1;
break;
case 2:
Statement-2;
break;
… ………….
… ………….
default:
statement-n
}
Example
#include<iostream>
using namespace std;
int main( )
{
char ch;
cout<<”Enter Character”;
cin>>ch;
switch(ch)
{
{
case ‘a’:
case ‘A’:
case ‘A’:
case ‘e’:
case ‘E’:
case ‘i’:
case ‘I’:
case ‘o’:
case ‘O’:
case ‘u’:
case ‘U’:
cout<<”It is vowel”;
break;
break;
default:
cout<<”It is consonant”;
}
}
return 0;
}
No comments:
Post a Comment