Replace Loops using Recursion: SUM with array

This is their answers based on the code below of recursion, I dont get where they got all random arrays, they don’t have one particular array in this problem. I am confuse all these arrays, dont we suppose to have just one array. Can you please help to explain how they got the answers and what happen if we pass n = 1, or 2, 3, 4, 5, 6 and so on…

sum([1], 0) should equal 0.

Passed

sum([2, 3, 4], 1) should equal 2.

Passed

sum([2, 3, 4, 5], 3) should equal 9.

Passed

Your code should not rely on any kind of loops ( for or while or higher order functions such as forEach , map , filter , or reduce .).

Passed

You should use recursion to solve this problem.

Your code so far


function sum(arr, n) {
// Only change code below this line
if (n <= 0) { 
return 0;
} else { 
return sum(arr, n - 1) + arr[n - 1];
}
// Only change code above this line
}

sum([1], 0);
sum([1], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

Just go through the code step by step and figure out what exactly n-1 and arr[n-1] are in each step.
Let’s take this example:

sum([2, 3, 4, 5], 3)

First function call:
sum([2, 3, 4, 5], 3) returns sum([2, 3, 4, 5], 2) + 4

Second function call:
sum([2, 3, 4, 5], 2) returns sum([2, 3, 4, 5], 1) + 3

Third function call:
sum([2, 3, 4, 5], 1) returns sum([2, 3, 4, 5], 0) + 2

Fourth function call:
Now n is 0, so
sum([2, 3, 4, 5], 0) from above doesn’t call the function again, but just returns 0

Now we can go backwards to see what those function calls actually evaluate to.

The third function call returns 0 + 2.
The second function call returns 0 + 2 + 3.
The first function call returns 0 + 2 + 3 + 4, which is the final result.

Recursion can be difficult to get your head around, just go through a number of simple examples (finding the factorial of a number with recursion, for example, just google how they do it) and visualise step by step what’s happening.

2 Likes