Search code examples
crecursiongreatest-common-divisor

find gcd of multiple user inputted values using C


#include <stdio.h>
int gcd()
{
int i,j,rem;
printf("Enter two integers: ");
scanf("%d%d",&i,&j);
while (i !=0)
{
    rem = j % i;
    j=i;
    i=rem;
} 
 printf("Greatest common denominator is %d\n",j);
}
int main()
{    

    gcd();
    return 0;
}

I am learning C using "C programming a modern approach 2nd edition." One of the exercises I had to create a function that takes in two numbers from a user and returns the gcd, I would like to be able to pass in multiple numbers but I don't know how to achieve this using C.


Solution

  • I recommend passing the numbers as an array of int and then applying the gcd algorithm on it recursively (preferably).

    int gcd(int *array, int n)
    {
        if(n == 0)
        {
            //find gcd using while loop of array[n] and array[n + 1]. store in result.
            return result;
        }
        return gcd(int *a, n -1);
    }