Website For Developers

Switch Statement in C++



• Switch statement in C++ is also used for decision-making.
• It is a good alternative for nested if-else statements.
• Switch statements are mostly used when there are many choices and only one should be executed.
• Note that we can do it with nested if as well but it becomes very difficult with nested if statement.


Syntax

switch(expression) {
  case 1:
    Statements...
    break;
  case 2:
    Statements...
    break;

  default:
    Statements...;
}

• Switch statement in C++ compares the value with multiple cases and execute the right one according to the condition.
• Each case represent one choice.
• If the condition matches with the case it executes the following case block.
• Switch statement in C++ can have an optional default case.
• The default case block is appeared in the end of the statements and it is executed only when the condition doesn't match with any of the cases.
• The break statement in each case is used to exit or terminate the switch statement.
break and default are optional but for the best practice, always use them.


switch statement in C++ example

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int option;
  cout<< "Select fruit name from below"<< endl;
  cout<< " 1)Apple \t 2)Mango \n 3)Banana \t 4)Orange"<< endl<< endl;
  cin>> option;

  switch(option) {
    case 1:
      cout<< "You Like Apples";
      break;
    case 2:
      cout<< "You Like Mangoes";
      break;
    case 3:
      cout<< "You Like Bananas";
      break;
    case 4:
      cout<< "You Like Oranges";
      break;
    default:
      cout<< "Please Select the Correct Option";
  }
  getch();
  return 0;
}

Output

Select fruit name from below
1)Apple     2)Mango
3)Banana     4)Orange

3
You Like Mangoes


Example#2

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int month;
  cout<< "Enter the number of a month: ";
  cin>> month;

  switch(month) {
    case 1:
      cout<< "January";
      break;
    case 2:
      cout<< "February";
      break;
    case 3:
      cout<< "March";
      break;
    case 4:
      cout<< "April";
      break;
    case 5:
      cout<< "May";
      break;
    case 6:
      cout<< "June";
      break;
    case 7:
      cout<< "July";
      break;
    case 8:
      cout<< "August";
      break;
    case 9:
      cout<< "September";
      break;
    case 10:
      cout<< "October";
      break;
    case 11:
      cout<< "November";
      break;
    case 12:
      cout<< "December";
      break;
    default:
      cout<< "Invalid Number";
  }
  getch();
  return 0;
}

Output

Enter the number of a month: 12
December