This is kind of a silly question but I came across this question and can't seem to understand how it works.
1 2 3 4 5 6 7 8 9 10 11
int Function (unsignedint val) {
if (val > 1) {
return Function(val - 1)*val;
}
else;
return 1;
}
This is supposed to calculate the factorial of a value val when >1. If I pass in 5 for example, it will go into the if statement and return (5-1)*5 which is not equal to 120. Can someone explain how this works?
> If I pass in 5 for example, it will go into the if statement and return (5-1)*5
No, read again. It would return Function(5-1) * 5, or Function(4) * 5 if you prefer.
Then you may realise that
5! = 1 * 2 * 3 * 4 * 5
1 * 2 * 3 * 4 = 4!
5! = 4! * 5
recursion works like calling any other function from inside a function.
the current function suspends and invokes the called function. That does what it does (maybe calling more functions) until it returns a result, and the caller resumes from that point.
It makes no difference to the machine that the function called is the same one it is currently inside.