In this tutorial let us discuss the switch
statements which is supported by C++ for handling decision-making.
The switch statement allows us to choose between several options for executing a block of code.
A switch statement checks a variable for equality against a range of values. Each value is referred to as a case, and each case checks the variable that is being switched on.
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// here the code will be executed only if
// expression is equal to constant2;
break;
.
.
.
default:
// here the code will be executed only if
//here the expression are not having a match with any constant
}
The expression will be evaluated once, then the results are compared with those of each case label.
Suppose, If a match is found, then the code following the matching label will be executed. For example, if the variable's value is constant2, the code following case constant2: will be executed until the break statement is encountered.
If no match is found, the code following default will be executed.
Using a switch statement let us create a calculator
#include <iostream>
using namespace std;
int main() {
char oper;
float num1, num2;
cout << " An operator should be entered (+, -, *, /): ";
cin >> oper;
cout << "Please enter two numbers: " << endl;
cin >> num1 >> num2;
switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator doesn't match with any case constant (+, -, *, /)
cout << "Error obtained! The operator is incorrect";
break;
}
return 0;
}
Output:
Output 1 An operator should be entered (+, -, *, /): + Please enter two numbers: 20 50 20 + 50 = 70 Output 2 An operator should be entered (+, -, *, /): - Please enter two numbers: 9 19 9 - 19 = -10 Output 3 An operator should be entered (+, -, *, /): * Please enter two numbers: 7 2 7 * 2 = 14 Output 4 An operator should be entered (+, -, *, /): / Please enter two numbers: 10 5 10 / 5 = 2 Output 5 An operator should be entered (+, -, *, /): ? Please enter two numbers: 2 3 Error obtained! The operator is incorrect
The switch...case statement is used in the preceding program to perform addition, subtraction, multiplication, and division.