I thought of declaring the variables first, and then finding the gcd and lcm. But when I tried to run, my code is not working. And the VS code is not even showing the errors. I am posting my code here:
#include <stdio.h>
int gcd(int a, int b)
{
for (int j = 1; j <= a && j <= b; ++j)
{
if (a % j == 0 && b % j==0)
return j;
}
}
int main ()
{
int i, n, pro=1, g, t, lcm;
int num[n];
printf ("Enter the no. of numbers: ");
scanf ("%d", &n);
for (i = 0; i <= n-1; i++)
{
printf ("Enter the number: ");
scanf ("%d", &num[i]);
}
g = gcd (num[0], num[1]);
for (t=2; t <= n; t++)
g = gcd(num[t], g);
for (i=0; i <= n-1; i++)
pro = pro*num[i];
lcm = pro/g;
printf ("GCD is %d\n", g);
printf ("LCM is %d", lcm);
return 0;
}
Well, I tried doing it again. The problem with my code was that the
return jwas in the loop, and thus, it was returning the value of j instead of giving the value of g.The corrected code: