Header Ads Widget



switch case in C

 What is switch case:-

                                  Switch case is a decision making construct which provide multiway alternative based on the selective expression . It has following syntax.

switch(expression )
      case label 1:  // statement if expr matches to the label 1
      case label 2: // statement if expr matches to the label 2
      case label n: // statement if expr matches to the label n
      default : // statement if expression does not matches with any label's


Expression:-   Expression is combination of operands and operators.

Working of switch case:-
  1. First of all expression is calculated.
  2. The result of the expression is matches with labels one by one (label 1,label 2,label 3 up to label n).
  3. If the result of the expression is matches with 'label i'  than the statement corresponding to the label i will be executed. If a break statement is encountered then flow of control goes outside of the switch block and continue to execute next statement after switch block.
     Note:-  if the value of the expression does not matches to any of the label the statement written under the default section will be executed . Default is optional in switch construct .

Example:-  Write a program to display a food menu to the user .  
int main()
int ch;
printf("1. Tea\n");
printf("2. Samosa\n");
printf("3. Cake\n");
printf("Enter your choice \n");
case 1: printf("OK , You will get tea\n ");
case 2 : printf("OK , You will get samosa\n");
case 3: printf("OK , You will get cake\n");
default: printf("You entered wrong choice\n");
return 0;

1. Tea
2. Samosa
3. Cake
Enter your choice
OK , You will get tea

Practice question based on switch case :-   Click here


Recommended Post:

Hackerearth Problems:-

Hackerrank Problems:-
Data structure:-

Key points:-


Post a Comment