In this article, we are going to learn about switch statement.
The Switch statement basically give us freedom of choice among many alternatives.You can choose from many options.
The syntax of the switch
statement in C++ is:
switch (var-name) { case <value1> : // code to be executed if // expression is equal to value1 break; case <value2> : // code to be executed if // expression is equal to value2 break; default : // code to be executed if // expression doesn't match any constant }
Flowchart of C++ switch case statement
Calculator using switch Statement :-
#include <iostream> using namespace std; int main(){ char calci; float dig1, dig2; cout << "Kindly enter operator (-, +, /, *): "; cin >> calci; cout << "Enter two numbers: " << endl; cin >> dig1 >> dig2; switch (calci){ case '-': cout << dig1 << " - " << dig2 << " = " << dig1 - dig2; break; case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; break; default: // operator is doesn't match any case constant (-, +, /, *) cout << "Error!!!! The operator is wrong "; } return 0; }
Output 1 :
Enter an operator (-, +, /, *): + Enter two numbers: 5.5 1.3 5.5-1.3 = 4.2
Output 2 :
Enter an operator (-, +, /, *): - Enter two numbers: 5.5 1.3 5.5 + 1.3 = 6.8
Output 3 :
Enter an operator (-, +, /, *): * Enter two numbers: 5.5 1.3 5.5/1.3 = 4.23
Output 4 :
Enter an operator (-, +, /, *): / Enter two numbers: 5.5 1.3 5.5 * 1.3 = 7.15
Output 5 :
Enter an operator (-, +, /, *): ? Enter two numbers: 5.5 1.3 Error!!!! The operator is wrong .
# Stepwise working of Program
oper
.
num1
and num2
.
+
, addition is performed on the numbers.
-
, subtraction is performed on the numbers.
*
, multiplication is performed on the numbers.
/
, division is performed on the numbers.