Home »
C++ Programs
C++ program to find the GCD (Greatest Common Divisor) of two numbers using class
Submitted by Shubh Pachori, on September 12, 2022
Problem statement
Given two numbers, we have to find the GCD (Greatest Common Divisor) of them using the class and object approach.
Example:
Input:
Enter 1st Number: 5
Enter 2nd Number: 45
Output:
GCD of 5 and 45 is 5
C++ code to find the GCD (Greatest Common Divisor) of two numbers using the class and object approach
#include <iostream>
using namespace std;
// create a class
class GCD {
// private data members
private:
int number_1, number_2;
// public member function
public:
// getNumbers() function to insert numbers
void getNumbers() {
cout << "Enter 1st Number: ";
cin >> number_1;
cout << "Enter 2nd Number: ";
cin >> number_2;
}
// gcd() function to find the gcd of
// two numbers inserted
void gcd() {
// a int type variable to store the GCD
int gcd;
// minimum value between number_1 and number_2 is stored in gcd
gcd = (number_1 < number_2) ? number_1 : number_2;
// a while loop to extract the GCD of both numbers
while (gcd > 0) {
// if condition to check if the both number is
// completely by the gcd
if ((number_1 % gcd == 0) && (number_2 % gcd == 0)) {
// break keyword to break the statements
break;
}
// decrement in the gcd by 1 in each iteration
gcd--;
}
// printing the GCD of both numbers
cout << "GCD of " << number_1 << " and " << number_2 << " is " << gcd
<< endl;
}
};
int main() {
// declaring an object
GCD G;
// calling getNumbers() function
// to insert numbers
G.getNumbers();
// calling gcd() function to find gcd
// of two numbers inserted
G.gcd();
return 0;
}
Output
RUN 1:
Enter 1st Number: 10
Enter 2nd Number: 2
GCD of 10 and 2 is 2
RUN 2:
Enter 1st Number: 17
Enter 2nd Number: 51
GCD of 17 and 51 is 17
Explanation
In the above code, we have created a class GCD, two int type data members number_1 and number_2 to store the numbers, and public member functions getNumbers() and gcd() to store the numbers and to find gcd of two numbers inserted.
In the main() function, we are creating an object G of class GCD, inputting the numbers by the user using the getNumbers() function, and finally calling the gcd() member function to check to find gcd of two numbers inserted. The gcd() function contains the logic to find the gcd of two numbers inserted.
C++ Class and Object Programs (Set 2) »