Write a C++ program using the concept of OOP to find the GCD of two numbers.
Algorithm:
- Create a GCD class with private variables num1, num2 to store the two numbers for which GCD is to be calculated.
- Define a public method calculate() in the class to calculate the GCD of the two stored numbers by using the Euclidean algorithm and return the result.
- In the main() function, prompt the user to enter two numbers.
- Create a GCD object with the two numbers entered by the user.
- Call the calculate() method of the GCD object to find the GCD of the two numbers.
- Print the GCD of the two numbers.
- End the program.
Coding:
#include <iostream> using namespace std; class GCD { private: int num1, num2; public: GCD(int n1, int n2) { num1 = n1; num2 = n2; } int calculate() { if (num2 == 0) { return num1; } return calculate(num2, num1 % num2); } }; int main() { int n1, n2; cout << "Enter first number: "; cin >> n1; cout << "Enter second number: "; cin >> n2; GCD gcd(n1, n2); cout << "GCD: " << gcd.calculate() << endl; return 0; }
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment