I was lookin for a code to implement the LCM of two numbers using recursion. Here is the code i found:
#include<stdio.h>
int lcm(int a, int b)
{
static int common = 1;
if (common % a == 0 && common % b == 0)
{
return common;
}
common++;
lcm(a, b); //call the function lcm recursively.
}
void main()
{
int a=5;
int b=6;
int c= lcm(a,b);
printf("\n%d",c);
}
I understand everything but the last line in the lcm(int a, intb) function
lcm(a,b);
According to me, for lets say input values 5,2 there will be 10 recursive calls made in the stack after which our base condition is reached. Now for the statement:
return common;
where does it return the value to? we are not really saving it anywhere in the 9th recursive call in the stack. How is it getting passed down the hierarchy and making its way to void main. If the recursive call was written as-
return lcm(a,b);
I understand how this works- we return the 10th recursive function call to 9th and then to 8th and so on... until it makes it way to void main when we return from the first time function was called.