Answer the question
In order to leave comments, you need to log in
How is x * func(x, n - 1) calculated (recursion)?
I almost don’t understand how recursion happens, how much I don’t read the material, everything is so abstract and not quite “logical”.
function func(x, n) {
if (n != 1) {
return x * func(x, n - 1);
} else {
return x;
}
}
alert(func(4, 3));
Answer the question
In order to leave comments, you need to log in
first pass: 3!=1 => 4 * (func(4, 3-1))
second pass: 2!=1 => 4 * (func(4, 1))
third pass: 1==1 => return 4
in the second pass substitute 4 => 4*4 = 16, return 16
in the first pass substitute 16 => 4 * 16 = 64
We break it down into steps (to understand how recursion works on a machine, you need to take into account the work of call stacks ):
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question