C++ Switch..case Statement
C++ Switch..case Statement
case Statement
In this tutorial, we will learn about switch statement and its working in C++
programming with the help of some examples.
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 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.
2. We then prompt the user to enter two numbers, which are stored in the
float variables num1 and num2 .
3. The switch statement is then used to check the operator entered by the
user:
o If the user enters + , addition is performed on the numbers.
o If the user enters - , subtraction is performed on the numbers.
o If the user enters * , multiplication is performed on the numbers.
o If the user enters / , division is performed on the numbers.
o If the user enters any other character, the default code is printed.
Notice that the break statement is used inside each case block. This terminates
the switch statement.
If the break statement is not used, all cases after the correct case are
executed.
CONDITIONS:
Screenshot the code and input/output. Take a photo while coding. Submit thru PDF! Good luck! <3