Calculator using Classes in C++
Last Updated :
23 Jul, 2022
Implementing a calculator in C++ using the concept of the classes.
Functions:
- Addition of two numbers.
- Difference between two numbers.
- Product of two numbers.
- Division of two numbers.
Approach:
- Declare local variables a, b for two numeric values.
- Enter the Choice.
- Takes two numbers, a and b.
- do-while jump to an operator selected by the user.
- Display the operation result.
- Exit
Examples:
Input: a = 5, b = 10, choice = 1
Output: Sum is 15
Input: a = 10, b = 4, choice = 3
Output: Product is 40
Below is the C++ program implementation of the above approach-
C++
#include <iostream>
#include <math.h>
using namespace std;
class Calculator
{
float a, b;
public :
void result()
{
cout << "Enter First Number: " ;
cin >> a;
cout << "Enter Second Number: " ;
cin >> b;
}
float add()
{
return a + b;
}
float sub()
{
return a - b;
}
float mul()
{
return a * b;
}
float div ()
{
if (b == 0)
{
cout << "Division By Zero" <<
endl;
return INFINITY;
}
else
{
return a / b;
}
}
};
int main()
{
int ch;
Calculator c;
cout << "Enter 1 to Add 2 Numbers" <<
"\nEnter 2 to Subtract 2 Numbers" <<
"\nEnter 3 to Multiply 2 Numbers" <<
"\nEnter 4 to Divide 2 Numbers" <<
"\nEnter 0 To Exit" ;
do
{
cout << "\nEnter Choice: " ;
cin >> ch;
switch (ch)
{
case 1:
c.result();
cout << "Result: " <<
c.add() << endl;
break ;
case 2:
c.result();
cout << "Result: " <<
c.sub() << endl;
break ;
case 3:
c.result();
cout << "Result: " <<
c.mul() << endl;
break ;
case 4:
c.result();
cout << "Result: " <<
c. div () << endl;
break ;
}
} while (ch >= 1 && ch <= 4);
return 0;
}
|
Output:
Addition of two numbers:
Subtraction of two numbers:
Multiplication of two numbers:
Division of two numbers:
Time complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...