I am trying to understand how recursion works. I have a basic idea, but the details remain unclear. Here is a simple javascript example:
function sumTo(n){
if (n > 1){
return n + sumTo(n-1)
} else {
return n
}
}
sumTo(3);
It is supposed to count all numbers in 3, and the result is 6 (1 + 2 + 3 = 6), but I do not understand how this works.
OK, we start with the if condition. 3> 1, so we return n and call the function again, but what happens inside the brackets?
It looks like this:
3 + sumTo (2) // 3 - 1 = 2
Or we do nothing with n and wait for the following function:
3 + sumTo (n - 1) // n will come later
I was told that the last function will return 1 to the top, but I don’t understand what it will do with this 1.
If there are several step-by-step explanations for the final layouts, please share.
I know that there are many similar questions, but I did not find any help.
UPD: , , , , . , , . , , - , .
, . http://www.integralist.co.uk/posts/js-recursion.html (1, 10) (2, 3).
function sum(x, y) {
if (y > 0) {
return sum(x + 1, y - 1);
} else {
return x;
}
}
sum(2, 3);
, if > 0. Y 3, . (x + 1, y - 1), i. . (2 + 1, 3 - 1), .. e sum (3, 2).
(3, 2). , y > 0. Y 2, . (x + 1, y - 1), i. . (3 + 1, 2 - 1), .. e sum (4, 1).
(4, 1). y > 0. Y 1, . (x + 1, y - 1), i. . (4 + 1, 1 - 1), .. e sum (5, 0).
(5, 0). y > 0 . if-else , x, 5. , (2, 3) 5.
sumTo();
function sumTo(n){
if (n > 1){
return n + sumTo(n-1)
} else {
return n
}
}
sumTo(3);
sumTo (3). n > 1: 3 > 1 , n + sumTo (n - 1), i. . 3 + sumTo (3 - 1), .. . 3 + sumTo (2).
, sumTo (2).
n > 1: 2 > 1 , n + sumTo (n - 1), i. . 2 + sumTo (2 - 1), i. . 2 + sumTo (1).
, sumTo (1).
, n > 1. 1 > 1 , , if-else, n, i. . 1. , sumTo (1) 1.
sumTo (1) sumTo (2), , , To (1) .
SumTo (2) n + sumTo (n-1), i. . 2 + sumTo (2 - 1), i. . 2 + sumTo (1), i. . 2 + 1. , sumTo (2) 3.
sumTo (2) sumTo (3), , , To (2) .
SumTo (3) n + sumTo (n-1), i. . 3 + sumTo (3 - 1), .. . 3 + sumTo (2), i. . 3 + 3. , sumTo (3) 6. , sumTo (3) 6.
, 3 n, n 1.
, .