Switch Case - Control Structure
How is a Switch case used in C++?
Use of "Switch Case" Control Structure.
Explanation
Switch statement compares the value of an expression against a list of integers or character constants.The list of constants are listed using the "case" statement along with a "break" statement to end the execution. If no conditions match then the code under the default statement is executed.
Syntax:
switch(expression)
{
case constant1:
Statements
break
case constant2:
Statements
break
.
.
default
Statements
}
Example :
#include <iostream.h> using namespace std; int main(void) { int day; cout << "Enter the day of the week between 1-7::"; cin >> day; switch(day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; default: cout << "Sunday"; break; } } |
Result :
Enter the day of the week between 1-7::7
Sunday
In the above Control Structure example the "switch" statement is used to find the day of the week from the integer input got from the user.