codescracker
c

C Program to Find HCF of n Numbers



« Previous Program Next Program »

In this article, you will learn and get code about finding HCF of n numbers. But before going through the program, I recomment you to visit Find HCF of Two Numbers once (if not visited). Because, the program given here is relatable to the program in that article.

HCF of n Numbers

Now let's create a program to find HCF of all the numbers given by user at run-time.

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
int main()
{
    int arr[10], n, mp, i, count;
    printf("Enter the Size: ");
    scanf("%d", &n);
    printf("Enter %d Numbers: ", n);
    for(i=0; i<n; i++)
        scanf("%d", &arr[i]);
    i=0;
    mp = arr[i];
    while(i<n)
    {
        if(mp<arr[i])
            mp = arr[i];
        i++;
    }
    while(1)
    {
        i=0;
        count=0;
        while(i<n)
        {
            if(arr[i]%mp==0)
                count++;
            i++;
        }
        if(count==n)
            break;
        else
            mp--;
    }
    printf("\nHCF(");
    for(i=0; i<(n-1); i++)
        printf("%d,", arr[i]);
    printf("%d) = %d", arr[i], mp);
    getch();
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is the sample run:

find hcf of n numbers c

Now supply the size say 3 and enter any 3 numbers say 8, 9, 25. Press ENTER key to see the following output:

c find hcf of n numbers

Here is another sample run for 2 numbers:

c program hcf of n numbers

This program is same as of previous program LCM of n Numbers in C. Except we have reverse the condition of if block from:

mp%arr[i]==0

to

arr[i]%mp==0

and the statement from:

mp++;

to

mp--;

Why these two is reversed is discussed in LCM & HCF of Two Numbers in C. The brief description is:

And as multiple of a number is greater than the number, whereas factor of a number is lower than the number. I hope you are gettting some idea about it. If not, then kindly visit:


« Previous Program Next Program »