Selection Statements

Selection Statements :

if statement :

It tests for a particular condition which if evaluates to be true, a block of statements is executed, else they are ignored.

Syntax :

if(expression)
{
statements..
}
If the expression evaluates to be true i.e. a  non zero value then statements are executed else ignored.

e.g.

if(ch==’A’)
printf(“n Given character is equal to A”);

An integers’ truth value is true when it stores non-zero value whereas it is false when it stores zero.

e.g.

if(x)
{
x++;//increments value of x when x is not equal to 0
}

if-else statement :

It tests for a particular condition which if evaluates to be true, a block of statements is executed else another statement is executed.

Syntax :

if(expression)
{
statements..1
}
else
{
statements..2
}

If expression evaluates to be true, Statements..1  is executed otherwise statement..1 is executed.

e.g.

if(x)
x++;
else
x–;
Above code increases value of x when it is non-zero and decrements value when it is 0.

Nested if :

An if statement that has another if statement in its if body or its else body or in its both bodies of if and else.

e.g.

if(x>0)
{
if((x*10)<100)
{
x++;
}
else
x–;
}

Switch Statement :

In this, it successively tests for the value of expression for a list of integer or character constants .

Syntax :

switch(expression)
{
case constant1 :
statement sequence 1;
break;
case constant2 :
statement sequence 2;
break;
:
:
case constantn :
statement sequence n;
break;
default :
default statement sequence;
}

break statement is to be used after every case otherwise statement of next case will be executed till break is not encountered.

e.g.
int n=1
switch(n)
{

case 1 : ++n;
case 2 : –n;
break;
case 3 : n=0;
break;
}

Since there is no break after case1, so statement of case2 is also executed.

  • Switch can only test for equality.
  • It can not handle a range of values like if-else. It can have a siingle value for every case.
  • It can not handle floating point tests
  • No two case statement can have identical values.
  • Switch are more efficient than if  in a situation that supports the nature of switch operation.

 

Nested Switches :  

It can also be nested in any of the case statements.

e.g.
switch(a)
{
case 1 : switch(b)
{
case 0 : printf(“Divide by zero error!!!”);
break;
case 1 : res=a/b;
}
case 2 : …statements…..
}

Leave a Reply

Your email address will not be published. Required fields are marked *