Please explain the operation of the recursive statement in the following code.
int factR(int n) { int result; if(n==1) return 1; result = factR(n-1) * n; return result; }
I understand that:
In the above statement, the factR(n-1) method calls itself to the end. Suppose we want to get a factorial of 6, which will be sent to this method as an argument. It will be accepted as parameter n , and then the value of n will be checked; if it is 1, then 1 will be returned. But if it is not 1, as in our case, where it is 6, then the recursion instruction will be executed.
Now the problem I am facing is that the first time n-1 becomes 5 and multiplies by n, which has a value of 6, then it becomes 30. Now, where will 30 GO be?
Then the method will call itself, and this time n-1 becomes 4, and then multiplied by n , which IF has the value "6", and then 4 * 6 = 24, which I think is incorrect. Because if we go this way, then in the next call the process will be something like: n-1 will become 3 * n, which IF has the same value, that is 6, then it will become 3 * 6 = 18. Then the following will happen call, and n-1 will become 2, if we multiply and assume that n has the value 6, then 2 * 6 = 12 and finally the call n-1 = 1 * n = 6. My point is that it is clear that n-1 will decrease the value of n-1 i.e. 6-1 = 5, then 5-1 = 4, then 4-1 = 3, then 3-1 = 2 and 2-1 = 1. BUT the question is what will be the value of n , which will be multiplied every time, when does the method call itself?
If you say that when the first multiplication will occur, i.e. "n-1" becomes 5, then it is multiplied by 6 = 30 and that 30 is stored in "n", and then in the next call 5-1 = 4 * 30 = 120, then 4-1 = 3 * 120 = 360, then 3-1 = 2 * 360 = 720 and finally 1 * 720 = 720, then how does Java determine to return the resulting value back to the variable n ?
If I put another statement to check what the value of the result variable is every time the method calls itself this way, for example:
int factR(int n) { int result; if(n==1) return 1; result = factR(n-1)*n ; System.out.println(result); return result; }
Then I get this output:
2 6 24 120 720 Factorial of 6 is 720
I do not understand how he produces 2 in his first call. Where did the value 2 come from, and then 6, 24, 120, and 720? I think I am very stuck in the code.