Write a C++ program using the concept of OOP to find the GCD of two numbers


Write a C++ program using the concept of OOP to find the GCD of two numbers.


Algorithm:

  1. Create a GCD class with private variables num1, num2 to store the two numbers for which GCD is to be calculated.
  2. 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.
  3. In the main() function, prompt the user to enter two numbers.
  4. Create a GCD object with the two numbers entered by the user.
  5. Call the calculate() method of the GCD object to find the GCD of the two numbers.
  6. Print the GCD of the two numbers.
  7. 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