C programming switch case


In this tutorial, you will learn about c programming switch case which is used when the decision is to made among lots of alternatives.

c programming switch case

Structure of switch statement

switch(expression)
 	{
 	case exp1: //note that instead of semi-colon a colon is used
 	       code block1;
 	       break;
 	case exp2:
 	       code block2;
 	       break;
 	.......
 	default:
 	       default code block;
 	}

How C programming switch case works then?


switch tests the value of expression against a list of case values successively. For example, in above structure, the expression is compared with all the case values. When exp1 matches the expression code block 1 will be executed and the break statement will cause an exit from the switch statement and no further comparison will be done.

However, if exp1 doesn’t matches with expression then exp2 will be compared and comparisons will be continued until the matching case. If no case matches with the expression the default code block will be executed.

Following block diagram explains more accurately the concept of switch case in C Programming.

switch case

Good Programming Practice
In switch..case case and the default statements can occur in any order but, it is good programming practice to write default at the end.

 

Example: C program to print the day of the week according to the number of days entered

#include <stdio.h>

int main()
{
  int n;
  printf("Enter the number of the day :");
  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:
      intf("Friday");
      break;
   case 7:
      printf("Saturday");
      break;
   default:
      printf("You entered wrong day");
      exit(0);
 }
 return 0;
}

Output

Enter the number of day : 5
Thrusday

Explanation:

The program asks the user to enter a value which is stored in variable n. Then the program will check for the respective case and print the value of the matching case. Finally, the break statement exit switch statement.

Common Programming Errors
When we forget to write break statement in a switch statement results in a logic error.