So I made this simple code with some help of a tutorial. Going through it i am not quite sure what happens at return faktor(tall-1)*tall
.
in the return statement the method calls itself and returns a value. What happens first? Does it call itself first, or does it first return the values, or do they both happen at the same time?
When it returns the values what happens then?
package enkelrekursjon1;
public class Enkelrekursjon1 {
public static void main(String[] args) {
System.out.print(faktor(3));
}
private static int faktor(int tall){
System.out.print(tall);
if (tall != 1){
return faktor(tall - 1)*tall;
}
return 1;
}
}
It works the same way a return statement returning a value always works:
faktor(tall - 1) * tall
)It can't possibly return before evaluating the expression, because there'd be no value to return.
So in your case, if you have call faktor(5)
you'll end up with a call stack of:
faktor(5)
-> calls faktor(4)
-> calls faktor(3)
-> calls faktor(2)
-> calls faktor(1)
-> returns 1
-> returns 1 * 2 (i.e. 2)
-> returns 2 * 3 (i.e. 6)
-> returns 6 * 4 (i.e. 24)
-> returns 24 * 5 (i.e. 120)
See more on this question at Stackoverflow