I am learning Java using the book Java: The Complete Reference.
Currently I am working on the topic Recursion.
Please Note: There are similar questions on stackoverflow. I searched them but I didn’t find the solution to my question. I am confused with the logic in the following program.
If I run the below program, it produces the correct output, but I didn’t understand the logic.
- I didn’t understand the logic in the following line : result = fact(n-1) * n;
- From my knowledge, If we pass the value of n=4 as shown in the below program,
- Then, 3 * 4 is stored in the result i.e., 12.
- Again, fact(n-1) is called. Then n becomes 3.
- Then the 2 * 3 is stored in the result replacing the previous 12.
-
I think you understood where I am stuck up/confused.
-
Thank you.
class Calculation { int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } public class Factorial { public static void main(String args[]) { Calculation obj_one = new Calculation(); int a = obj_one.fact(4); System.out.println("The factorial of the number is : " + a); } }
resultis a local variable of thefactmethod. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.So when fact is invoked with 3 as argument, you can imagine that its result is