try simulating this function step by step manually for a small integer input say "3"
1st time call:
3 is not equal to 0.
so this function will return the value 3 x factorial(2).
2nd call:
2 is not equal to 0.
so this sub function will return the value 2 x factorial(1).
3rd call:
1 is not equal to 0.
so this sub-sub function will return the value 1 x factorial(0).
4th call:
0 is equal to 0!
so this sub-sub-sub function will return the value 1 (finally!)
back to 3rd call
sub-sub finction returns 1 x factorial(0) = 1 x 1 = 1.
back to 2nd call
sub finction returns 2 x factorial(1) = 2 x 1 = 2.
back to 1st call
finction returns 3 x factorial(2) = 3 x 2 = 6.// final returned value to main function.
does function store 3,2,1 numbers in memory until value become "0" ?
when does the function do this ??
(i can understand the previous steps)
back to 3rd call
sub-sub finction returns 1 x factorial(0) = 1 x 1 = 1.
back to 2nd call
sub finction returns 2 x factorial(1) = 2 x 1 = 2.
back to 1st call
finction returns 3 x factorial(2) = 3 x 2 = 6.
Recursion is a beauty once you get the hang of it.
does function store 3,2,1 numbers in memory until value become "0" ?
It technically does not hold the values in memory, this is done by the function itself.
1 2 3 4 5 6 7
long BackwardNum(long num)
{
int t = log10(num);
if (t == 0)//base case
return num;
return (((num%10) * pows_n(10, t)) + BackwardNum(num/10));//recursion
}
The beauty of recursion lies in how it reduces the amount of work needed to be done via each new call itself. The function only returns it's first value once the base case has been reached.
Think of it as a challenge which is to climb up a set of stairs to retrieve football equipments. Each stair requires you to be wearing an item from the stair above it(recursion) with the (n-1)th stair requiring the football. Once you get to the nth stair(base case), you now have the foot-ball, so you start making your way down the stairs(this is the part of recursion you can't see), you present the football to the lower stair and in turn you get a helmet(in case you fall...), this will continue to happen until you get to the last set of stairs with full football gear and ready to go.