Write a C++ Program to Find GCD

As a C++ programmer, finding the greatest common divisor (GCD) of two numbers is a common task that you may need to perform.

In this tutorial, I will show you how to write a simple C++ program to find the GCD of two numbers.

To find the GCD of two numbers, we will use the Euclidean algorithm.

The Euclidean algorithm is an efficient method for finding the GCD of two numbers, and it works by repeatedly subtracting the smaller number from the larger number until the two numbers are equal. The GCD is then equal to the common value.

Let’s take a look at the C++ program to find the GCD of two numbers using the Euclidean algorithm.

#include <iostream>
using namespace std;

int main()
{
    int num1, num2;
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    while (num1 != num2)
    {
        if (num1 > num2)
            num1 = num1 - num2;
        else
            num2 = num2 - num1;
    }

    cout << "GCD of the two numbers is " << num1 << endl;

    return 0;
}

In this program, we first declare two integer variables num1 and num2 to store the input values.

We then prompt the user to enter two numbers using the cout and cin statements.

Next, we use a while loop to repeatedly subtract the smaller number from the larger number until the two numbers are equal.

If num1 is greater than num2, we subtract num2 from num1. Otherwise, we subtract num1 from num2.

When the two numbers are equal, we exit the while loop and print the GCD using the cout statement.

That’s it! You now have a simple C++ program to find the GCD of two numbers using the Euclidean algorithm.