Answer to Question #181380 in C++ for DHARMVEER SINGH

Question #181380

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.


1
Expert's answer
2021-04-14T19:07:22-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS