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)? nAnswer:
We will create program using class and objects .
Follow the following steps:
- Create class Calculator .
- Define three data members named operand1(int/double),operand2(int/double),operator(char)
- Define a constructor to initialize data members.
- Define input function to assign values to data members.(It can be used optionally)
- Define a Function to display the result.
Program:
#include <iostream>
using namespace std;
class calculator
{
private:
int operand1,operand2,result;
char oprator;
public:
//Default Constructor
calculator()
{
operand1=0;
operand2=0;
oprator='+';
}
//Parameterised Constructor
calculator(int op1,int op2,char opr)
{
operand1=op1;
operand2=op2;
oprator=opr;
}
int doCalculation()
{
result=0;
switch(oprator)
{
case '+':
result=operand1+operand2;
break;
case '-':
result=operand1-operand2;
break;
case '*':
result=operand1*operand2;
break;
case '/':
result=operand1/operand2;
break;
}
return result;
}
void display()
{
cout<<operand1<<" "<<oprator<<" "<<operand2<<" = "<<result;
}
};
int main()
{
int x=0;
int o1,o2;
char opr;
do{
cout<<"\nEnter the expression in format(operand1 oprator operand2)";
cin>>o1>>opr>>o2;
//Object Creation
calculator c(o1,o2,opr);
//Calling the member functions
c.doCalculation();
c.display();
//To continue non-negative number is taken if -1 is entered then exit
cout<<"\nTo continue enter positive number else -1";
cin>>x;
}
while(x!=-1);
return 0;
}