Write a C++ program using the concept of OOP to perform the mathematical operation between two numbers.
Algorithm:
- Create a Calculator class with private variables num1 and num2 to store the two numbers.
- Define public methods add(), subtract(), multiply(), and divide() in the class to perform the respective mathematical operations on the stored numbers.
- In the main() function, prompt the user to enter two numbers.
- Create a Calculator object with the two numbers entered by the user.
- Call the various methods of the Calculator object to perform the mathematical operations and store the results in variables.
- Print the results of the mathematical operations.
- End the program.
Coding:
#include <iostream> class Calculator { private: double num1, num2; public: Calculator(double n1, double n2) { num1 = n1; num2 = n2; } double add() { return num1 + num2; } double subtract() { return num1 - num2; } double multiply() { return num1 * num2; } double divide() { return num1 / num2; } }; int main() { double n1, n2; std::cout << "Enter first number: "; std::cin >> n1; std::cout << "Enter second number: "; std::cin >> n2; Calculator c(n1, n2); std::cout << "Addition: " << c.add() << std::endl; std::cout << "Subtraction: " << c.subtract() << std::endl; std::cout << "Multiplication: " << c.multiply() << std::endl; std::cout << "Division: " << c.divide() << std::endl; return 0; }
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment