switch

An alternative selection statement, giving the possibility to test an expression against multiple int or char values, is switch. Given an int variable:
int a;
the switch statement:
switch(a)
{
case 1:
     cout << "you entered 1";
     break;
case 2:
     cout << "you entered 2";
     break;
case 3:
     cout << "you entered 3";
     break;
default:
     cout << "you did not enter either 1, 2 or 3";
}
checks whether a’s value is either 1, 2, or 3. In which case the statements following the succeeding case are executed. In case the value is neither 1, nor 2, nor 3, the default statements are executed. The break following each case is needed to avoid all statements associated with the following cases to be executed until a break is actually found (which is what by definition would happen).

Example


#include <iostream>
using namespace std;

int main()
{   
     cout << "Enter a value, please ";
     int a;
     cin >> a;

     switch(a)
     {
     case 1:
           cout << "you entered 1";
           break;
     case 2:
           cout << "you entered 2";
           break;
     case 3:
           cout << "you entered 3";
           break;
     default:
           cout << "you did not enter either 1, 2 or 3";
     }
}

Output

Enter a value, please 3
you entered 3