Im having a difficult time understanding HOW exactly the factorial based recursion example works. The example is given in the tutorials section of this website and I've reproduced it below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
elsereturn 1;
}
int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
}
Now, can someone walk me through this step-by-step? How does this work and why doesn't the output simply display a 1 because of the elsereturn 1?
Well, the way it works that the function factorial will return, if a is greater than one, the product of a and what factorial would return when passed a-1. The function call of a-1 would then call a-2, and so on, until you end up with a-a+1=1. That factorial function would return one. The factorial function above it (a-a+2) would then multiply a and what was returned (1), yielding 2, and pass it above to factorial(a-a+3). This would repeat until you end up with factorial(a).
@Ispil: Thank you for your response. So my understanding is that the 1 is actually returned to the factorial function itself, correct? Because return values always return to the function that called them, and in this case the function calls itself and hence the value of 1 is returned to itself. Am I understanding this correctly?
@Andywestken: Im completely lost as to what you are doing in that code. And I am entirely unfamiliar with "string(depth...)".
string(depth, ' ') is using the string (size_t n, char c); form of the string constructor, so I'm saying create a string with depth spaces, to get the line indenting to work (depth = recursion depth, which I added as a parameter to the function.)
The extra code is just to print out the function name and what it returns so should be easy enough to follow.