switch
(case) statements are a block of code that acts in the same manner as an if-else-if
ladder.
The switch
statement matches the variable value against every case
statement and returns the value accordingly. If there’s no match, the default
case executes.
The format is neater and easier to read than a block of multiple if-else
statements.
switch(var)
{
case 1:
// code for case 1
break;
case 2:
// code for case 2
break;
default:
// code for default
}
Note: The
break
statements at the end of the code for each branch are essential! If thebreak
statement is missing, the subsequent case code blocks will start execution until theswitch
block has finished execution or until anotherbreak
statement is encountered.
The value provided in each case can be integers or characters.
Duplicate cases are not allowed.
The default
case is optional and will only be executed when none of the cases are true
.
The break
statement is not needed in the default
case.
It is possible to nest switch
statements, but it is not recommended as it may reduce the readability of the code.
Here is a code for a very simple calculator:
Please add a simple equation without white spaces as input, like: 4+2, 5-6, 3*3, 4/8, etc.
#include <iostream>using namespace std;int main() {char op;int first;int second;int ans = -1;cout << "Please input first number: ";cin >> first;cout << first << endl;cout << "Please input operator (+,-,*,/): ";cin >> op;cout << op << endl;cout << "Please input second number: ";cin >> second;cout << second << endl;cout << "Equation: " << first << " " << op << " " << second << endl;switch(op){case '+':ans = first + second;break;case '-':ans = first - second;break;case '*':ans = first * second;break;case '/':ans = first / second;break;default:cout << "Incorrect Operator" << endl;}cout << "the answer is: " << ans;return 0;}
Enter the input below