C++ Switch Statement

  • Switch statement works with an expression or variable which can be of integer or character data type.
  • In Switch statement, there can be multiple cases whose values are compared with the expression used with switch statement.

Syntax


switch(Expression)
{
    case value1:
                           Statement1;
    case value2:
                           Statement2;
    case value3:
                           Statement3;
    :
    :
    default:
                  Statement N;
}
Statement A;


Here, switch is a keyword used to specify start of switch statement.
Expression is any int or char variable or expression on which switch works.
case is a keyword which is used to specify any case in switch.
value1, value2, value3 are various case value which are compared with Expression.
If value of expression matches with value1, then Statement1 will be executed. If value of expression matches with value2, then Statement2 will be executed. If value of expression matches with value3, then Statement3 will be executed and so on.
If value of expression doesn't match any value then default case will be executed

Program to show use of switch statement.



#include<iostream.h>
#include<conio.h>
void main()
{
     clrscr();
     int d;
     cout<<"Enter a value between 1 and 7 =";
     cin>>d;
    switch(d)
    {
             case 1:
                        cout<<"\n Sunday";
                        break;
             case 2:
                        cout<<"\n Monday";
                        break;
             case 3:
                        cout<<"\n Tuesday";
                        break;
             case 4:
                        cout<<"\n Wednesday";
                        break;
             case 5:
                        cout<<"\n Thrusday";
                        break;
             case 6:
                        cout<<"\n Friday";
                        break;
             case 7:
                        cout<<"\n Saturday";
                        break;
             default:
                        cout<<"\n Wrong Choice";
                        break;
     } 
    getch();
}



Output


Enter a value between 1 and 7 = 2
Monday

Back To Top