Replace Loops using Recursion

``````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
}
``````

So I got it to pass and I understand we are ultimately adding a certain number of items in the array. However, I Still do not understand the flow of the code, specifically where it says “return sum(arr, n-1)”. Can someone tell me exactly what this is doing in the most simple words possible? Preferably walking through a scenario. I have looked at many other posts on here and on youtube and I am still struggling with this.

I really think you can tell us

Let’s say I call the function as:

``````sum([7,8,9], 2);
``````

Since `n` is not less than or equal to `0` then your function is going to execute the code in the `else` block:

``````return sum(arr, n - 1) + arr[n - 1];
``````

Based on the values I passed into the function when I called it above, show us what values are really in that `return` statement. In other words, replace the variable names with their actual values. This is the first step to understanding how the recursion is working.

Ok so just to clarify, on the first go around where n = 2 in your example, it jumps to the else statement (because n is not less than or equal to 0). Then in the else statement, the “return sum(arr, n-1)” it is decrementing the 2 to 1, and then adding the value at index arr[n-1]? And then repeats this until n = 0 in the if statement. Is that correct?

1 Like

Yes, it sounds like you are explaining it correctly.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.