




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A comprehensive guide on the switch statement in c++ programming language. It explains the syntax, how it works, and provides a flowchart for better understanding. The document also includes an example of a simple calculator built using the switch statement. It is a valuable resource for students and developers looking to master the switch statement in c++.
Typology: Schemes and Mind Maps
1 / 8
This page cannot be seen from the preview
Don't miss anything!





Switch Statement How does the switch statement work? How does the switch statement work?
Dev-C++
The switch statement allows us to execute a block of code among many alternatives. You can do the same thing with the if...else statement. However, the syntax of the switch statement is much easier to read and write. Syntax switch (expression) { case constant1: // code to be executed if // expression is equal to constant1; break; case constant2: // code to be executed if // expression is equal to constant2; break;
default: // code to be executed if // expression doesn't match any constant }
The expression is evaluated once and compared with the values of each case label. If there is a match, the corresponding code after the matching label is executed. For example, if the value of the variable is equal to constant2, the code after case constant2: is executed until the break statement is encountered. If there is no match, the code after default: is executed. Note : We can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.
Example: Create a Calculator using the switch Statement // Program to build a simple calculator using switch Statement #include
cout << "Error! The operator is not correct"; break; } return 0; } Output 1 Enter an operator (+, - , *, /): + Enter two numbers:
2.3 + 4.5 = 6. Output 2 Enter an operator (+, - , *, /): - Enter two numbers:
2.3 - 4.5 = - 2. Output 3 Enter an operator (+, - , *, /): * Enter two numbers:
2.3 * 4.5 = 10.
Percentage >= 95% : Grade A+ Percentage >= 90% : Grade A Percentage >= 85% : Grade B+ Percentage >= 80% : Grade B Percentage >= 70% : Grade C+ Percentage >= 60% : Grade C Percentage >= 40% : Grade D Percentage < 40% : Grade F Expected Output: