Switch Statement in C


Switch Statement

 

The nested form of an if… else statement or an else if statement in a program sometimes becomes so complex that, the programmer himself/herself gets confused as to whether the conditions are complete or incomplete.

For such a situation, the 'C' programming language provides another decision-making statement switch.

It is also called a multiple-branch selection statement because it allows a choice of multiple values for a single condition.

 

Its general syntax is as follows –

switch (expression or variable)
{
   case variable equals this:
   do this;
   break;
   case variable equals this:
   do this;
   break;
   case variable equals this:
   do this;
   break;
   default:
   do this
}

 

The working of switch statement can be understood from the diagram given below-

 

switch statement

 

 

// Example of switch statement without a break statement.

 

# include < stdio.h >

# include < conio.h >

main ()

{

int i;

clrscr();

printf(“Enter 1 or 2 ”);

scanf(“%d”, &i);

switch(i)

{

case 1:

printf (“It is case 1.”);

case 2:

printf (“It is case 2.”);

default:

printf (“It is the default case.”);

}

getch();

}

 

The expected output is:
Enter 1 or 2
1
It is case 1.
It is case 2.
It is the default case.
 
Enter 1 or 2
2
It is case 2.
It is the default case.
 
Enter 1 or 2
4
It is the default case.

 

// Example of the switch statement with a break statement.

 

# include < stdio.h >

# include < conio.h >

main ()

{

int i;

clrscr();

printf(“Enter 1 or 2 ”);

scanf(“%d”, &i);

switch(i)

{

case 1:

printf (“It is case 1.”);

break;

case 2:

printf (“It is case 2.”);

break;

default:

printf (“It is the default case.”);

}

getch();

}

 

The Expected output is:
Enter 1 or 2
1
It is case 1.
 
Enter 1 or 2
2
It is case 2.
 
Enter 1 or 2
3
It is the default case.

 

Read Also: PHP Switch Statement