In this article iam going to talk about C++ Switch Statement Example, also you can watch the video training for this article at the end . so switch statement is used when we have multiple conditions and we need to perform different action based on the condition. For example if we have different conditions and we want to execute a block of code based on certain condition. In that case we need to use switch statement. Also you can use else if condition, but it is good idea if you have multiple conditions you can use switch statement.
Also you can check more articles on c++ programming language
1: C++ Introduction & Program Structure
2: C++ Variables And Data Types
The syntax of switch statement
1 2 3 4 5 6 7 8 9 10 11 12 |
switch (variable or an integer expression) { case constant: //C++ code ; case constant: //C++ code ; default: //C++ code ; } |
Some main points for switch statement
- You can use non-numerical values with the switch statement.
- Duplicate case values are not allowed.
- The cases do not have to be in order, as long as you use proper requirements and syntax.
- The cases cannot have the same value, as this will result in a duplicate value error.
- You don’t have to use a break statement for each case.If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.
OK now this is our example and our example is based on the user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include<iostream> using namespace std; int main() { char grade; cout << "Please enter your grade" << endl; cin >> grade; switch (grade) { case 'A': cout << "Excellent" << endl; break; case 'B': cout << "Very Good" << endl; break; case 'C': cout << "Good" << endl; break; case 'D': cout << "Your passed " << endl; break; case 'E': cout << "Your failed " << endl; break; default: cout << "Invalid Grade " << endl; } return 0; } |
At the top of this code first we have created a variable of type char. after that we are going to get the input from the user and store that input in the char variable. after that we are checking the cases, after run this will be the result.
1 2 3 4 |
Please enter your grade A Excellent Press any key to continue . . . |
Also you can watch the complete video for C++ Switch Statement Example
Subscribe and Get Free Video Courses & Articles in your Email