Switch Statement

  • The second of C++’s selection statements is the switch.
  • The switch provides for a multiway branch. Thus, it enables a program to select among several alternatives.
  • Although a series of nested if statements can perform multiway tests, for many situations the switch is a more efficient approach.
  • switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

 

Syntax

switch(integer expression) 
{
   case constant 1 : 
        do this ; 
   case constant 2 : 
        do this ; 
   case constant 3 : 
        do this ; 
   default : 
        do this ;
}

 Flow Diagram

Flow Diagram of switch statement

Example

// platters.cpp 
// demonstrates SWITCH statement 
#include using namespace std; 

int main() 
{ 
 int speed; //turntable speed
 
 cout << “
Enter 33, 45, or 78: “;
 cout > speed; //user enters speed 
 switch(speed) //selection based on speed
  {
   case 33: //user entered 33 
     cout << “LP album
”; 
     break; 
  case 45: //user entered 45 
    cout << “Single selection
”; 
    break; 
  case 78: //user entered 78 
    cout << “Obsolete format
”; 
    break; 
 } 
return 0; 
} 

Output:

Enter 33, 45, or 78: 
45 
Single selection