Index « Previous Next »

Question

Write a program that prompts the user to input two numbers and display its HCF.

The Highest Common Factor (HCF) also called the Greatest Common Divisor (GCD) of two whole numbers, is the largest whole number that's a factor of both of them.

Source Code

#include <stdio.h>

int main()
{
    int dividend, divisor, rem, hcf;

    printf("Enter two numbers : ");
    scanf("%d%d", &dividend, &divisor);

    do
    {
        rem = dividend % divisor;
        if (rem == 0)
        {
            hcf = divisor;
        }
        else
        {
            dividend = divisor;
            divisor = rem;
        }
    }while (rem != 0);

    printf("HCF is : %d", hcf);

    return 0;
}

Output

Enter two numbers : 16 4
HCF is : 4