Reputation: 1
Hi I am trying to write a code in C to find the GCD for more than 2 numbers. However, when I compile and run the code, the GCD is always 0. Would appreciate if anyone can help. Thank you.
#include <stdio.h>
static int gcd(int x, int y)
{
int r;
if (x <= 0 || y <= 0)
return 0;
while ((r = x % y) != 0)
{
x = y;
y = r;
}
return y;
}
int main (void)
{
int A[5];
int g = A[0];
int i;
int n;
printf ("How many elements are there? \n")
scanf ("%d", &n);
printf ("Input the elements. \n");
for (i = 0; i < n; i++)
{
scanf ("%d", &A[i]);
}
for (i = 1; i < n; i++)
g = gcd(g, A[i]);
printf ("GCD is: %d \n");
return 0;
}
Upvotes: 0
Views: 1738
Reputation: 765
You need a ;
after the first printf
.
You need to declare A
with n
elements after you read the number of elements n
.
You have to write the g
after ",
in your last printf
.
This is how I think your main should look like:
int main (void)
{
int i;
int n;
printf ("How many elements are there? \n");
scanf ("%d", &n);
int A[n];
printf ("Input the elements. \n");
for (i = 0; i < n; i++)
{
scanf ("%d", &A[i]);
}
int g = A[0];
for (i = 1; i < n; i++)
g = gcd(g, A[i]);
printf ("GCD is: %d", g);
return 0;
}
Upvotes: 0
Reputation: 182819
You set g
equal to A[0]
before you set A[0]
to any particular value.
Upvotes: 2