HCF/GCD of Two Numbers Program in C Language

To find the HCF of two numbers in C programming, take any of the two numbers in hcf, and other number in a temp variable. Decrement the largest of these two by the other until the values in these two variables are same. When they are same, we have HCF in both of these variables.

C Program

In the following program, we read two numbers to n1 and n2, and find their HCF.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n1, n2;
    printf("Enter first  number : ");
    scanf("%d", &n1);
    printf("Enter second number : ");
    scanf("%d", &n2);
    
    int hcf = n1, temp = n2;
    while(hcf != temp) {
        if(hcf > temp)
            hcf = hcf - temp;
        else
            temp = temp - hcf;
    }
    
    printf("HCF : %d\n", hcf);
}

Output

Enter first  number : 15
Enter second number : 10
HCF : 5
Program ended with exit code: 0

Output

Enter first  number : 4
Enter second number : 8
HCF : 4
Program ended with exit code: 0

Conclusion

In this C Tutorial, we learned how to find HCF of two numbers in C programming, with examples.