Question Continuation
int factorial(int n) {
if(n == 0)
return 1;
else
return n * factorial(n - 1);
}
Provide a brief explanation why this recursive function works.
Show all steps involved in calculating factorial(3) using the function defined.
Answer:
1. Brief explanation why this recursive function works.
First, the recursive method factorial is defined.
This is the means through with the machine identifies the method.
The method is defined as integer, the machine will regard it as integer.
When the factorial is called from anywhere that has access to it, which in this case is within the factorial class itself. This means you can call it from the main method, or you can call it from the factorial method itself. It's just a function call that, well, happens to call itself.
2. Steps to calculate factorial(3)
1 First, 3 is assigned to n.
2. At line 2, the machine checks if n equals 0
3. If yes, the machine prints 1
4. Else; it does the following from bottom to top
factorial(3):
return 3*factorial(2);
return 2*factorial(1):
return 1;
Which gives 3 * 2 * 1 = 6
5. Then it prints 6, which is the result of 3!