Switch Statement


Switch statement

Switch statement is a control statement that allows us to choose only one choice among the many given choices. it is a control statement used to make a selection between many alternatives.

When switch statement is used

Syntax:-
       switch(choice)
      {
         case value 1:
         Block -1;
     break;
         case value 2:
          Block – n;
     break ;
         default:
         Block - d
    }

Some rules of switch statement

The expression that follows the keyword switch must be evaluated to an integer .
The expression that follows the keyword case should not contain any variables
Two or more case labels with same value not allowed
Two or more case labels can be associated with same statements.
Example:-
         int i ;     char c ;    float f ;    double d ;

  • switch (i)
                 //valid
  • switch(i+10)
                 //valid
  • switch(i+5.5)
                 //invalid
  • switch(c+10)
                 //valid
  • switch(c+d)
                 //invalid d is double floating point not allowed.
  • case4:
                 //invalid space must be
  • case'+'
                 //valid
  • case A
                 //invalid
  • case choice
                 //invalid only one character is allowed

W.A.P to design a calculator.

#include<stdio.h>
#include<conio.h>
void main()
 {
  int ch;
  printf(“press any key 1 to 3 “);
  scanf(“%d”,&ch);
  switch(ch)
 {
  case 1:
  printf(“one”);
  break;
  case 2:
  printf(“Two”);
  break;
  case 3:
  printf(“Three”);
  break;
  default:
  printf(“press only 1 to 3”);
 }

Output

Press any key 1 to 3
2
Two

W.A.P to print days of week.

 #include<stdio.h>
 #include<conio.h>
 void main()
 {
   int n;
   printf("press any key");
   scanf("%d",&n);
   switch(n)
  {
   case 1:
   printf("sunday");
   break;
   case 2:
   printf("Monday");
   break;
   case 3:
   printf("Tuesday");
   break;
   case 4:
   printf("Wednesday");
   break;
   case 5:
   printf("Thrusday");
   break;
   case 6:
   printf("Friday");
   break;
   case 7:
   printf("Saturday");
   break;
   default:
   printf("press valid key");
  }
   getch();
  }

Output

press any key
6
Friday

W.A.P to check odd or even using switch.

 #include<stdio.h>
 #include<conio.h>
  void main()
  {
   int n;
   printf("enter a no");
   scanf("%d",&n);
   r=n%2;
   switch(r)
  {
   case 0:
   printf("Even");
   break;
   default:
   printf("odd");
  }
   getch();
 }

Output

enter a no
    5
  odd