-->

Switch Statement

Switch Statement
Switch Statement
  • In real life we often face situations, where we need to make a choice, between a number of alternatives rather than only one or two
  • Serious C programming is the same as real life, the choice we are asked to make is, more complicated than merely selecting between two alternatives.
  • C programming provides a special control statement that allows us to handle such cases effectively; rather than using a series of ‘if’ statements.
  • The switch statement, tests the value of a given expression, against the list of case values.

The general form of switch statement is:
switch(integer expression)
{
case constant 1:
                do this;
case constant 2:
                do this;
case constant 3:
                do this;
default:
                do this;
}

Example 1:
Sample C program, using switch statement

#include<stdio.h>
int main(void)
{
int i=2;
switch(i)
{
case 1:
printf(“I am in case 1”);
case 2:
printf(“This is the second one”);
case 3:
printf(“This is the third case”);
default:
printf(“your are in default”);
}
return 0;
}

OUTPUT
This is the second one
This is the third case
You are in default



Related Posts

Subscribe Our Newsletter