C++ for Beginners: C++ Program to Find GCD

Hits: 20

(C++ programming Example for Beginners)

C++ Program to Find GCD

Examples on different ways to calculate GCD of two integers (for both positive and negative integers) using loops and decision making statements.

 


The largest integer which can perfectly divide two integers is known as GCD or HCF of those two numbers.


Example 1: Find GCD using while loop


#include <iostream>
using namespace std;

int main(){
    int n1, n2;

    cout << "Enter two numbers: ";
    cin >> n1 >> n2;
    
    while(n1 != n2)
    {
        if(n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }

    cout << "HCF = " << n1;
    return 0;
}

Output

Enter two numbers: 78
52
HCF = 26

In above program, smaller number is subtracted from larger number and that number is stored in place of larger number.

This process is continued until, two numbers become equal which will be HCF.


Example: 2. Find HCF/GCD using for loop


#include <iostream>
using namespace std;

int main(){
    int n1, n2, hcf;
    cout << "Enter two numbers: ";
    cin >> n1 >> n2;

    // Swapping variables n1 and n2 if n2 is greater than n1.
    if ( n2 > n1) {   
        int temp = n2;
        n2 = n1;
        n1 = temp;
    }
    
    for (int i = 1; i <=  n2; ++i) {
        if (n1 % i == 0 && n2 % i ==0) {
            hcf = i;
        }
    }

    cout << "HCF = " << hcf;
    return 0;
}

The logic of this program is simple.

In this program, small integer between n1 and n2 is stored in n2. Then the loop is iterated from i = 1 to i <= n2 and in each iteration, value of i is increased by 1.

If both numbers are divisible by i then, that number is stored in variable hcf.

When the iteration is finished, HCF will be stored in variable hcf.

 

 

C++ for Beginners: C++ Program to Find GCD

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.