The problem in if-statement is the complexity to read and follow. Even it may be confuse the programmer who designed it. The switch statement tests the value of the variable with a list of case values and when a match is found, and then the block of that particular case will be executed.
Syntax:
switch(expression)
{
case: 1
block-1
break;
case: 2
block-2
break;
default:
default-block
break;
}
As is the above syntax we will give the expression in the form of variable. And according to that given value it will executes the case. If any of the case is not matched then the default case will be executed. And we have used the break statement which will help to exit from the switch statement. The break will skip the rest of the cases for comparisons, and this saves execution time.
Program:
/*77.PROGRAM TO DISPLAY MONDAY TO SUNDAY USING SWITCH CASE*/
#include<iostream.h>
#include<conio.h>
void main()
{
int n;
clrscr();
cout<<“Enter any number b/w 1 and 7: “;
cin>>n;
switch(n)
{
case 1:
cout<<“Sunday is the first day of the week”;
break;
case 2:
cout<<“Monday is the second day of the week”;
break;
case 3:
cout<<“Tuesday is the third day of the week”;
break;
case 4:
cout<<“Wednesday is the fourth day of the week”;
break;
case 5:
cout<<“Thursday is the fifth day of the week”;
break;
case 6:
cout<<“Friday is the sixth day of the week”;
break;
case 7:
cout<<“Saturday is the seventh day of the week”;
break;
default:
cout<<“You have entered a wrong choice”;
}
getch();
}