# What is sum(arr,n-1)+arr[n-1] means?

Tell us what’s happening:
Describe your issue in detail here.

``````  **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
}
``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36`

Challenge: Replace Loops using Recursion

1 Like

This is simple recursion, and best visualized with pen and paper. When you give the function `sum` an array `arr`, and the array length `n`, unless you have reached the beginning of the array index, `sum(arr,n-1)+arr[n-1]` is returned, meaning:

• the function `sum` calls itself (recursion), but passes in a different index `n`, this function call eventually returns a value.
• to the recursive call, `sum` adds the value of `arr[n-1]`

let us try with a test case of arr=[1,2,3,4,5] and n=5.
1st call to `sum`, return sum(arr,4)+arr,
2nd, return sum(arr,3)+arr,
3rd, return sum(arr,2)+arr,
4th, return sum(arr,1)+arr,
5th, return sum(arr,0)+arr,
6th, return 0 (since n<=0)

Then the last result of 6th call is added to each of the previous returns.
5th, return 0+1=1,
4th, return 1+2=3,
3rd, return 3+3=6,
2nd, return 6+4=10,
1st (the original call to `sum`) finally get 10+5=15.

Therefore running sum([1,2,3,4,5],5) returns 15, and the function`sum` adds up the values within the passed array backwards from the index passed in.

2 Likes

Thanks a lot… This is well understood when written on paper with your explanation. Im still struggling with something here and i feel like theres a fundamental concept that i should understand that i just missed. But when you say “5th, return 0+1=1”, i dont understand since above “5th, return sum(arr,0) + arr”… im not sure how that equates 0 + 1.

My misunderstanding i think lies in how im expecting the math to work out. Does this mean sum(arr,0) is equal to 0?

Yes. Literally that function call says ‘add 0 elements from the array’. The sum of nothing is 0.

1 Like

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