C Switch Statement

The switch statement is used to perform different actions based on different expression. The switch statement basically evaluates a switch expression, and based on the switch expression value when the case matched then the associated block of code is executed until break statement or end case statement. And if there is no matched case then the code associated with default will be executed. Also note that the case value must be integer or character constant.

The syntax of switch case as follows :
switch (expression) {
  case value_1:
    // code to be executed if expression = value_2
    break;
  case value_2:
    // code to be executed if expression = value_2
    break;
  ...........
 
  case value_n:
    // code to be executed if expression = value_n
    break;
 
  default:
    // code to be executed if none of values are matched
}
The break statement indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases. The basic example of switch statement is as follows :
#include <stdio.h>

int main() {
  int num;
  printf("Enter Number between 1 to 7 : ");
  scanf("%d", &num);

  switch(num) {
    case 1:
      printf("1st day is Monday.\n");
      break;
    case 2:
      printf("2nd day is Tuesday.\n");
      break;
    case 3:
      printf("3rd day is Wednesday.\n");
      break;
    case 4:
      printf("4th day is Thursday.\n");
      break;
    case 5:
      printf("5th day is Friday.\n");
      break;
    case 6:
      printf("6th day is Satuarday.\n");
      break;
    case 7:
      printf("7th day is Sunday.\n");
      break;
    default:
      printf("Please enter number between 1 to 7.\n");
  }

  return 0;
}
Output :

Enter Number between 1 to 7 : 4
4th day is Thursday.

Next Topic :