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 > calci;
cout > dig1 >> dig2;
switch (calci){
case '-':
cout
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
-
We first prompt the user to enter the desired operator. This input is then stored in the
char variable named
oper.
-
We then prompt the user to enter two numbers, which are stored in the float
variables
num1 and num2.
-
The switch statement is then used to check the operator entered by the user.
-
If the user enters
+ , addition is performed on the numbers.
-
If the user enters
- , subtraction is performed on the numbers.
-
If the user enters
* , multiplication is performed on the numbers.
-
If the user enters
/ , division is performed on the numbers.
-
If the user enters any other character, the default code is printed.