Switch case statement in C++

We will learn to use switch case statement in C programming. After completing this tutorial you will be able to use switch case in almost any scenario.

If we need to choose option using only single value or constant then we use switch statement. 

switch statement in c++

Syntax of switch statement:

switch (constant)
​{
    case value1:
        // code to be executed if case is equal to value1;
        break;

    case value2:
        // code to be executed if case is equal to value2;
        break;
        .
        .
        .
    default:
        // code to be executed if case doesn't match any value
}

In above code, if the constant is equal to case 1, the code of first case will execute. If first case is not matched, it will try with and so on if non of the case is matched the code of default: block executes. 

If first case is matched and after execution of code, if break;  statemet is not found the switch statement will not be terminate instead it again check all the case until last case executes.

Switch statement flow chart

Example of switch statement

//program to print the day of the week according to the number of days entered
# include <iostream>
using namespace std;

int main()
{
  int n;
  cout << "Enter the number of the day : ";
  cin >> n;
  switch (n)
  {
   case 1:
      cout << "Sunday";
      break;
   case 2:
      cout << "Monday";
      break;
   case 3:
      cout << "Tuesday";
      break;
   case 4:
      cout << "Wednesday";
      break;
   case 5:
      cout << "Thrusday";
      break;
   case 6:
      cout << "Friday";
      break;
   case 7:
      cout << "Saturday";
      break;
   default:
      cout << "You entered wrong day";
      exit(0);
 }
 return 0;
}

Output

Enter the number of day : 1
Sunday