Q33. Discuss about conditional control statements.
Answer:
Conditional control statements check the condition and execute the statements depending upon the result which can be either true or false. Types of conditional statements are as follows,
1. if
2. if-else
3. switch.
1. if Statement
This statement performs an action if the condition is true, otherwise it skips that action and executes other statement.
Syntax
if (condition)
{
statement-1;
}
statement-next;
Here, if the condition is satisfied, then statement-1 is executed followed by statement-next. Otherwise, statement-1 block is skipped and only statement-next is executed.
Figure (1): Flowchart of Simple if Statement
Example
#include<iostream.h>
#include<constream.h>
void main( )
{
int n;
clrscr();
cout<<“Enter the value for
n:”<<endl;
cin>>n;
if((a%2) == 0)
{
cout <<n<<“is an even
number”<<endl;
}
getch( );
}
Output
2. if-else Statement
This statement is an extension of simple ‘if‘ statement. Here, the ‘if‘ statement executes when boolean expression is true and ‘else’ statement executes when expression is false.
Syntax
if(condition)
{
statement-1;
}
else
{
statement-2;
}
statement-next;
In the above syntax, statement-1 will be executed followed by statement-next when the condition is true. Otherwise, statement-2 will be executed followed by statement-next.
Example
#include<iostream.h>
#include <constream.h>
void main( )
{
int n;
clrscr();
cout<<“Enterthe value of n:”;
cin>>n;
if(n%2 = = 0)
{
cout <<n<<“is an even
number”;
}
else
{
cout <<n<< “is an odd
number”;
}
getc();
}
3. switch Statement
A ‘switch’ statement is a multi-way decision making statement. It compares the expression value with a list of constants or cases. Only the corresponding statements of the matched case will be executed.
Syntax
switch (expression)
{
case constant1: statement-1;
break;
case constant2: statement-2;
break;
...................
cease constantn: statement-n;
break;
default: default-statement;
break;
}
statement-next;
The value of the expression is evaluated and it is compared with constant case values. When match is found, the corresponding statement block associated with the case is executed. If no match is found then the default case will be executed.
Figure: Flowchart of switch Statement.
Example
#include<iostream.h>
#include<constream.h> :
void main()
{
char.c;
clrscr();
cout << “Enter a
character:”;
cin >> c;
cout<<endl;
switch(c)
{
case ‘a’:
cout << “a is a vowel”;
break;
case 'e':
cout << “e is a vowel”;
break;
case ‘I’:
cout << “i is a vowel”;
break;
case ‘o”:
cout << “o is.a vowel”;
break;
case ‘u’:
cout << “u is a vowel”.
break;
default:
cout << “The alphabet
entered is a consonant”;
}
getch( );
}
Output