The switch statement can used as an alternative to if...else statements when the value of a single variable needs to provide multiple choices. The following code demonstrates the switch statement.
switch(Day)
{
case 1:
cout << "Sunday";
break;
case 2:
cout << "Monday";
break;
case 3:
cout << "Tuesday";
break;
case 4:
cout << "Wednesday";
break;
case 5:
cout << "Thursday";
break;
case 6:
cout << "Friday";
break;
case 7:
cout << "Saturday";
break;
default:
cout << "Invalid Day";
}
As can be seen in the previous switch statement, the optional default statement can be included to provide a branch if none of the other cases execute. In a switch statement, it is not necessary to use braces for each case, even if you have multiple lines of code to execute. It is important to remember to put a break after each case, otherwise all remaining cases will execute. The next program demonstrates another switch statement.
Program 10.1 – Switch Statement |
#include <iostream>
main() |
Output |