- C++ program to find factorial using recursive function
- C++ program to convert binary number to decimal and decimal to binary
- C++ program to display prime numbers between two intervals
- C++ program to print Pascal’s and Floyd’s triangle
- C++ program to print star pyramid patterns
- C++ Hello World Program
- C++ program to display Fibonacci series using loop and recursion
- C++ program to find area of the circle
- C++ program to calculate the area of the square with and without using function
- C++ program to encrypt and decrypt the string
- C++ program to convert temperature
- C++ program to check prime number
- C++ program to check palindrome number
- C++ program to make simple calculator using switch case
- C++ program for time conversion (convert time format)
- C++ program to find GCD or HCF
- C++ program to check for the power of two
- C++ program to check Armstrong number
- C++ program to check leap year
- C++ program to find LCM of two numbers

In this example, you will learn about different ways of C++ program to find GCD or HCF using for and while loop of two integers.

The largest number that can perfectly divide both numbers is known as Greatest Common Divisor (GCD) or Highest Common Factor (HCF).

There are many ways to find GCD. In this article, we will discuss two simple logic.

```
//C++ program to find greatest common divisor (GCD)
#include <iostream>
using namespace std;
int main()
{
int x, y, i, gcd;
cout << "Enter two integer values:" << endl;
cin >> x >> y;
for (i = 1; i <= x && i <= y; i++)
{
if (x % i == 0 && y % i == 0)
gcd = i;
}
cout << "\nGCD of " << x << " and " << y << " is: " << gcd << endl;
return 0;
}
```

**Output**

**Explanation**

The value of `i`

is increased till it is equal to `x`

or `y`

.

In every iteration, `if`

condition checks whether `x`

and `y`

are both perfectly divisible by `i`

or not.

If `x`

and `y`

are perfectly divisible then the value of `i`

is stored in `gcd`

.

```
//C++ program to find GCD or HCF using while loop
#include <iostream>
using namespace std;
int main()
{
int x, y, temp, gcd;
cout << "Enter two integer values:" << endl;
cin >> x >> y;
//while loop for calculation of GCD
while (y != 0)
{
temp = y;
y = x % y;
x = temp;
}
gcd = x;
cout << "\nGCD or HCF of given numbers: " << gcd << endl;
return 0;
}
```

**Output**

aEnter two integer values:96 108 GCD or HCF of given numbers: 12

**Explanation**

In the above program, `while`

loop continues till `y`

is not equal to zero.

The value of `y`

is calculated as `x % y`

.