C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Variables, Construct & Looping  >  Conditional Constructs (switch..case Construct)
 

C++ has a built-in multiple branch selection statement called switch. The switch statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.

The following program illustrate the usage of a switch statement:

//Program 2.1
//This program demonstrates the usage of a switch construct
#include<iostream.h>
void main()
{
int iDay;
cout<<"Enter the day of the week:";
cin>>iDay;
switch(iDay)
{
case 1:
{
cout<<"The day is Sunday"<<endl; //The value in variable iDay is one
break;
}
case 2:
{
cout<<"The day is Monday"<<endl; //The value in variable iDay is Two
break;
}
case 3:
{
cout<<"The day is Tuesday"<<endl; //The value in variable iDay is three
break;
}
case 4:
{
cout<<"The day is Wednesday"<<endl; //The value in variable iDay is four
break;
}
case 5:
{
cout<<"The day is Thrusday"<<endl; //The value in variable iDay is five
break;
}
case 6:
{
cout<<"The day is Friday"<<endl; //The value in variable iDay is six
break;
}
case 7:
{
cout<<"The day is Saturday"<<endl; //The value in variable iDay is seven
break;
}
default:
{
cout<<"You have entered the wrong day"<<endl;
break;
}
}
}


The keyword switch is followed by the variable in parentheses:

switch(iDay)

Each case keyword is followed by a case constant or character types. For example:

case 1:

or

case 'a':

The data type of the case constant should match with that of the switch variable. Before entering the switch construct, the program should assign a value to the switch variable.

 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.