Write a C++ program to define a class for calculator with data members as number1 and number2 (both as double) and methods as add(), sub(), mul(), div(). Create an array of 5 objects of calculator. Use parameterized constructor to initialize the values. Display output of all four arithmetic operations.
#include <iostream>
using namespace std;
class calculator
{
public:
calculator(double number1, double number2);
double add() {return number1 + number2;}
double sub() {return number1 - number2;}
double mul() {return number1 * number2;}
double div();
private:
double number1;
double number2;
};
calculator::calculator(double number1_, double number2_) : number1(number1_), number2(number2_)
{}
double calculator::div()
{
if(number2 == 0) return 0;
else return number1 / number2;
}
int main()
{
calculator calc[5] = { calculator(1, 3), calculator(10, 0), calculator(13, 8), calculator(7, 24), calculator(8, 3) };
for(int i = 0; i < 5; i++)
{
cout << "**************************************" << endl;
cout << "Add() is: " << calc[i].add() << endl;
cout << "Sub() is: " << calc[i].sub() << endl;
cout << "Mul() is: " << calc[i].mul() << endl;
cout << "Div() is: " << calc[i].div() << endl;
}
cout << endl;
return 0;
}
Comments
Leave a comment