C program to find GCD (HCF) of any two numbers

Write a C program enter two numbers and find the HCF(Highest Common Factor) using for loop. How to find GCD(HCF) of any two given numbers using loops in C programming. C program to print GCD(HCF).
Example:HCF of 12 and 30 is 6

Required knowledge

Basic C programming, If else, Conditional operator, For loop

HCF(Highest Common Factor)

HCF is the greatest number that divides exactly two or more numbers. HCF is also known as GCD(Greatest Common Divisor) or GCF(Greatest Common Factor).
HCF of two numbers

Program to find GCD (HCF)

 * C program to find HCF(Highest Common Factor) of two numbers

#include <stdio.h>

int main()
    int i, num1, num2, min, hcf=1;

     * Reads two numbers from user
    printf("Enter any two numbers to find HCF: ");
    scanf("%d %d", &num1, &num2);

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

    for(i=1; i<=min; i++)
         * If i is factor of both number
        if(num1%i==0 && num2%i==0)
            hcf = i;

    printf("HCF of %d and %d = %d\n", num1, num2, hcf);
    return 0;

Also don't forget to check this program using recursive approach - C program to find GCD (HCF) of any two numbers.

Enter any two numbers to find HCF: 12
HCF of 12 and 30 = 6

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment