C program to print HCF (GCD) of two numbers

C program to print HCF (GCD) of two numbers

In this tutorial, you will learn how to write a program to print the HCF (GCD) of two numbers by using for loop conditional statement.

Our Problem Statement:

Here, we have to find HCF for the two user-given numbers. HCF/GCD or Highest Common Factor is the greatest number that divides each of two or more numbers.

Example:

Input: 128 and 48

Output: 16

As both 128 and 48 have 16 as their highest common factor.

In the below code, we are using for-loop to iterate the given numbers and checking the divisibility for both the numbers for that iteration. When we reach an iteration where the conditions are met we break the loop for our output.

#include <stdio.h>
int main() {
    int num1, num2, i, gcd;
    printf("Enter two positive integers: ");
    scanf("%d %d", &num1, &num2);
    for (i = 1; i <= num1 && i <= num2; i++) {
        if (num1 % i == 0 && num2 % i == 0) {
            gcd = i;
        }
    }
    printf("GCD of %d and %d is %d\n", num1, num2, gcd);
    return 0;
}

Output:

Enter two positive integers: 128
48
GCD of 128 and 48 is 16