Write a C++ program create a calculator for an arithmetic operator (+, -, *, /).

/*
Problem statement:
Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program
should take two operands from user and performs the operation on those two operands
depending upon the operator entered by user. Use a switch statement to select the operation.
Finally, display the result.
Some sample interaction with the program might look like this:
Enter first number, operator, second number: 10 / 3
Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n
*/
#include<iostream>
using namespace std;
class calc
{
private:
int result;
public:
calc();//constructor definition
int addition(int,int);
int subtraction(int,int);
int multiplication(int,int);
int division(int,int);
};
calc::calc()//constructor
{
result=0;
}
int calc::addition(int num1,int num2)//addition function
{
result=num1+num2;
return result;
}
int calc::subtraction(int num1,int num2)//subtraction function
{
result=num1-num2;
return result;
}
int calc::multiplication(int num1,int num2)//multiplication function
{
result=num1*num2;
return result;
}
int calc::division(int num1,int num2)//division function
{
if(num2!=0)
{
result=num1/num2;
return result;
}
else
{
if(num2==0)//cannot divide by zero condition
cout<<"Cannot divide by a ZERO\n";
}
}
int main()
{
char op,flag;
int num1,num2,t;
calc obj;
do
{
cout<<"Enter in format :NUMBER1 <space> OPERATIOR <space> NUMBER2\n";
cin>>num1>>op>>num2;
switch (op)
{
case '+': {
t=obj.addition(num1,num2);
cout<<"\nThe addition is "<<t<<"\n";
break;
}
case '-': {
t=obj.subtraction(num1,num2);
cout<<"\nThe difference is "<<t<<"\n";
break;
}
case '*': {
t=obj.multiplication(num1,num2);
cout<<"\nThe multiplication is "<<t<<"\n";
break;
}
case '/': {
t=obj.division(num1,num2);
if(t!=0)
cout<<"\nThe quotient is "<<t<<"\n";
break;
}
}
cout<<"\nDo you want to continue(y/n)?\n";
cin>>flag;
}while(flag=='y');
if (flag=='n')
return 0;
}
/*
-------------------------------------------output---------------------------------------------
Enter in format :NUMBER1 <space> OPERATIOR <space> NUMBER2
3 + 123
 
The addition is 126
 
Do you want to continue(y/n)?
y
Enter in format :NUMBER1 <space> OPERATIOR <space> NUMBER2
23 - 1234
 
The difference is -1211
 
Do you want to continue(y/n)?
y
Enter in format :NUMBER1 <space> OPERATIOR <space> NUMBER2
45 / 5
 
The quotient is 9
 
Do you want to continue(y/n)?
y
Enter in format :NUMBER1 <space> OPERATIOR <space> NUMBER2
45 / 0
Cannot divide by a ZERO
 
Do you want to continue(y/n)?
y
Enter in format :NUMBER1 <space> OPERATIOR <space> NUMBER2
345 * 2      
 
The multiplication is 690
 
Do you want to continue(y/n)?
n
 
------------------------------------------------------------------------------------------------
*/

Post a Comment

0 Comments