Calculator using the switch case – Computer Sir Ki Class

Code Learning #CPP#2059

## Calculator using the switch case

A program that works like a calculator for two input numbers and works for most arithmetic operations like addition, subtraction, multiplication, division etc.

## Learning Objectives

• Learning to use switch-case for special symbols.
• Tricky use of switch case for mathematical operations.

## Source Code

 #include using namespace std; int main ( ) { double a,b; char op; cout<<"Enter two numbers : "; cin>>a>>b; cout<<"Enter operator (+,-,*,/) : "; cin>>op; switch (op) { case '+': cout <

## Run Output

``````Enter two numbers : 12.34 11.78
Enter operator (+,-,*,/) : *
12.34*11.78=145.365

-OR-
Enter two numbers : 34.2 2.2
Enter operator (+,-,*,/) : /
34.2/2.2=15.5455
``````

## Code Understanding

double a,b;
Here we are declaring variables for input values. We are taking them as double so that sufficiently large fractional values can also be operated upon.

char op;
In this variable we shall collect the operator symbol as character.

cout<<“Enter two numbers : “; cin>>a>>b;
Here we are collecting the uperands.

cout<<“Enter operator (+,-,*,/) : “; cin>>op;
Here we are getting the operator symbol from the user in a char data type variable.

switch (op)
This selects between the operator character provided by the user.

case ‘+’: cout <<a<<“+”<<b<<“=”<<a+b; break;
Here we are doing it for + operator. The operands we assume are to be used in the order as given by the user.

case ‘-‘: cout <<a<<“-“<<b<<“=”<<a-b; break;
case ‘*’: cout <<a<<“*”<<b<<“=”<<a*b; break;
case ‘/’: cout <<a<<“/”<<b<<“=”<<a/b; break;
Similarly all operators cases are handled.

default: cout <<“Error in input”;
This is used when operator symbol is not correctly given

## Notes

• The basic +,-,*,/ operators work on all number data types but the modulus operator (%) does not work on fractional data types like float and double. You are advised to use fmod() function of the math library.

## Common Errors

• Some students are not comfortable writing calculation operations in the cout chain. To avoid error one can also write the case expressions like this.double res;
case ‘+’:  res=a+b;
cout <<a<<“+”<<b<<“=”<<res; break;
case ‘-‘:  res=a-b;
cout <<a<<“-“<<b<<“=”<<res; break;
and so on.

Note that the res variable has been reused. This is possible as only one of the cases has to be used at any time.

Suggested Filename(s): calc-sc.cpp

sunmitra| Created: 31-Dec-2017 | Updated: 15-Sep-2018|

×