# C++ program to find the GCD (Greatest Common Divisor) of two numbers using class

Given two numbers, we have to find the GCD (Greatest Common Divisor) of them using the class and object approach.
Submitted by Shubh Pachori, on September 12, 2022

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.

What's New (MCQs)

Top Interview Coding Problems/Challenges!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.