Skip to main content

C Programming #8 (Case Control Instruction)

In Programming we come across some situations where we have to choose from number of alternatives and choice should be specific to condition so the control statement that allow us to make a decision from number of choice is called as switch or we can say switch-case as they are used together.

The switch statement looks like :
switch (integer expression)
{
case constant 1:
do this;
case constant 2:
do this;
case constant 3:
do this;
default:
do this;
}
In these case do this is the command statement that is to be followed when case is satisfied
Example:
#include<stdio.h>
int main()
{
int i=2;
switch(i)
{
case 1:
printf("I am in case 1\n");
case 2:
printf("I am in case 2\n");
case 3:
printf("I am in case 3\n");
default:
printf("I am in default");
}
return 0;
}
Output of the program will be :
I am in case 2
I am in case 3
I am in default
But this is not the output we needed this program should give us I am in case 2
So in this program the control is not stopping at case 2 so here we have to use break statement
The required program is
#include<stdio.h>
int main()
{
int i=2;
switch(i)
{
case 1:
printf("I am in case 1\n");
break;
case 2:
printf("I am in case 2\n");
break;
case 3:
printf("I am in case 3\n");
break;
default:
printf("I am in default");
}
return 0;
}
Tips and traps:

  • It is not necessary for case statement to be in sequence like case 1,case 2.
  • We can also use it like case 22,case 7,case 132.
  • We can also use character in switch like case 'a',case 'b'.

Comments