Hi I have a little understanding how recursion works but I don't see how this factorial code works
so when x == 1 it returns 1,then where is 1 returned to,so how does the math actually take place if lets say I called the function with 5 as the arguement?
Thanks
1 2 3 4 5 6 7 8
int factorial(int x){
if(x==1){
return 1;
}
return x * factorial(x - 1);
}
You do understand that calling factorial(1) returns 1. Good.
The condition is obviously false when x>1, isn't it? Then the line 6 happens.
For factorial(2) the x is 2, and line 6 returns 2 * factorial(1)
We already know that factorial(1) returns 1, so the line actually returns 2 * 1.
For factorial(3) the x is 3, and line 6 returns 3 * factorial(2)
We already know that factorial(2) returns 2, so the line actually returns 3 * 2.
But we don't start "group up", we start from top.
factorial(5) returns 5 * factorial(4)
that evaluates to 5 * ( 4 * factorial(3) )
that evaluates to 5 * ( 4 * ( 3 * factorial(2) ) )
...