C Program to Find GCD or HCF of Two Numbers


Lets write a C program to find Greatest Common Divisor(GCD) or the Highest Common Factor(HCF) of 2 integer numbers entered by the user.

Related Read:
while loop in C programming
Relational Operators In C
Logical Operators In C

GCD or HCF: Largest Integer that can divide both the numbers without any remainder or with 0 as remainder.

Logic to Find GCD or HCF of Two Numbers

Variable count is initialized to 1. Next, we ask the user to enter 2 integer numbers. We check the smallest of the 2 numbers and we iterate the while loop until variable count is less than or equal to this smallest number.

Inside while loop we keep incrementing the value of count by one for every iteration. We also check if both numbers entered by the user is perfectly divisible by the value present in count. If we get any such number, we store it inside the variable gcd. And after the control exits while loop we print the value present in variable gcd.

Source Code: C Program to Find GCD or HCF of Two Numbers

 
#include < stdio.h >

int main()
{
    int num1, num2, gcd, count = 1;

    printf("Enter 2 positive integers\n");
    scanf("%d%d", &num1, &num2);

    while(count <= num1 && count <= num2)
    {
        if(num1 % count == 0 && num2 % count == 0)
        {
            gcd = count;
        }
        count++;
    }

    printf("GCD or HCF of %d and %d is %d\n", num1, num2, gcd);

    return 0;
}

OR

 
#include < stdio.h >

int main()
{
    int num1, num2, gcd, count = 1, small;

    printf("Enter 2 positive integers\n");
    scanf("%d%d", &num1, &num2);

    small = (num1 < num2)? num1 : num2;

    while(count <= small)
    {
        if(num1 % count == 0 && num2 % count == 0)
        {
            gcd = count;
        }
        count++;
    }

    printf("GCD or HCF of %d and %d is %d\n", num1, num2, gcd);

    return 0;
}

Output 1:
Enter 2 positive integers
24
60
GCD or HCF of 24 and 60 is 12

Here we check the smallest number among the two numbers entered by the user. We iterate through the while loop until value of count is less than or equal to that smallest number of the 2 numbers entered by the user.
Biggest of Two Numbers Using Ternary Operator: C

C Program to Find GCD or HCF of Two Numbers


[youtube https://www.youtube.com/watch?v=4ZbDj6BrM-Q]

YouTube Link: https://www.youtube.com/watch?v=4ZbDj6BrM-Q [Watch the Video In Full Screen.]


For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *