public static void main (String[] args)
{
System.out.println(factorial(5));
}
public int factorial(int n)
{
if(n <= 1){
return 1;
}
else{
return n * factorial(n - 1);
}
}
I wrote the above directly in here so may not compile but think it does.
Can anyone breiefly explain how this works in the sence that how is it stored? It starts off by calculating 5 * (5-1), then down to 4 * (4-1) then 3 * (3-1)….. until it gets to 1 which will just return 1 right? sorry for being so sketchy i would just be interested to find out how
this works exactly
thanks
but as it works it out – it gets the values for the individual stages
5*(5-1)
4 * (4-1)
…
…
…
how are these stored and then retrieved back or am i missing something?
Imagine you are the computer, and someone hands you a paper with
written on it. You then execute the procedure, looking at the argument. Since it’s > 1, you write
on another piece of paper and “hand it to yourself”, waiting until you get the answer to that one before proceeding.
Again you execute the procedure. Since 2 is still > 1 you write
on yet another piece of paper and hand it to yourself, waiting until you get the answer to this one before proceeding.
Again, you execute the procedure. This time the input is 1, so you take the first branch and return 1. The invocation that was processing factorial(2) now has an answer so it multiplies 2 by that answer (1) and returns. Now the invocation that was handling factorial(3) gets its answer (2) and multiplies it by 3, giving 6. It then returns that answer to the person who started the whole operation.
If you imagine that you kept the pieces of paper in a stack in front of you as you were working, that is a visualization of the “stack” in the computer’s memory. Each recursive invocation stores the parameter (and any temporary variables) on its own piece of paper (stack frame) literally arranged as a pushdown stack just like the papers, one on top of the other.