In C++ programming, the switch statement is used to execute one block of code out of multiple blocks of code.
Switch statement Syntax in C++.
switch (expression) { case /* constant-expression */: /* code */ break; case /* constant-expression */: /* code */ break; default: /*expression not matching with any constant-expression */ /* code */ }
Working of switch statement:
- The switch expression is evaluated once and then compared with the constant-expression value of each case.
- If the correct match is found, the associated code of that particular case is executed until the break statement in encountered.
- When there is no matching expression then default code block is executed.
Switch Statement Flowchart
Example: This C++ program is printing the weekday based on the number.
//C++ Example switch statement #include<iostream> using namespace std; int main(){ int day; cout<<"Enter a day number: "; cin>>day; switch (day) { case 1: cout<<"Today is Monday"; break; case 2: cout<<"Today is Tuesday"; break; case 3: cout<<"Today is Wednesday"; break; case 4: cout<<"Today is Thursday"; break; case 5: cout<<"Today is Friday"; break; case 6: cout<<"Today is Saturday"; break; case 7: cout<<"Today is Sunday";
break; default: cout<<"No match found"; } return 0; }
Enter a day number: 5
Today is Friday
Output 2:Enter a day number: 9
No match found
Enter a day number: 9
No match found
Here in output 2, the default code block is executed because there is no matching constant-expression matching with value 9 in the switch case.
Use break keyword in switch.
The break statement is optional in switch and it is used to come out of switch block and ignore the execution of reset of the cases. If you don't mention break statement at the end of each switch case then compiler keep executing next case until it found a break statement.
Example:
//C++ Example switch statement #include<iostream> using namespace std; int main(){ int day; cout<<"Enter a day number: "; cin>>day; switch (day) { case 2: cout<<"\nToday is Tuesday"; break; case 3: cout<<"\nToday is Wednesday"; /*break statement is missing here*/ case 4: cout<<"\nToday is Thursday"; break; case 7: cout<<"\nToday is Sunday"; break; default: cout<<"\nNo match found"; } return 0; }
Enter a day number: 3
Today is Wednesday
Today is Thursday
Here in the output, you can observe that when we have selected a case not having a break statement then code executed the next block also and stop when it found a break statement.
Note: You can perform the same task using if...else statement in C++ but in few cases switch case is use because it is more easy to read and understand. (alert-passed)
Few examples of switch case problem:
No comments:
Post a Comment