I've started learning C and programming in general relatively recently and we were told to make a program that finds the GCD and LCM of two numbers using recursion.
Now after some grinding I managed to get this together.
#include<stdio.h>
int gcd(int a,int b);
int main()
{
int a,b,l,temp;
printf("Enter two numbers :\n");
scanf("%d%d",&a,&b);
if(a<b)
{
temp=a;
a=b;
b=temp;
}
l=gcd(a,b);
printf("GCD = %i\nLCM = %i",l,a*b/l);
return 0;
}
int gcd(int a,int b)
{
static int c;
c=a%b;
a=b;
b=c;
if(c!=0)
{
gcd(a,b);
}
else
return a;
}
Now for some reason unknown to me, the function does not work without the "else". More specifically like this:
int gcd(int a,int b)
{
static int c;
c=a%b;
a=b;
b=c;
if(c!=0)
{
gcd(a,b);
}
return a;
}
Although irrelevant to the assignment I feel like I should understand what the problem here is. As a novice I would appreciate any and all help.
I apologize in advance if the question is too stupid or the code too messy.