# Replace Loop with Recursion

Can anyone tell me or guide me into the correct explanation for this? I am very new to coding, and I want to understand how to solve this problem.

``````
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([2,3,4,5],3)
// sum([2,3,4,5], 3-1 = 2] + arr[3-1 = 2])
// sum(2+3) -- sum of first 2 values = (5) + arr (2nd index of arr is 4))
// so: 5 + 4 = 9

// sum([2,3,4], 1)
// sum([2,3,4],1-1 = 0)(since it is 0, it returns 0) + arr[1-1 = 0])
// arr is 2 because it is the zereoth index of arr
// so: 0 + 2 = 2)
``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15`

Challenge: Replace Loops using Recursion

Hello there.

Do you have a question?

If so, please edit your post to include it in the Tell us what’s happening section.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more information you give us, the more likely we are to be able to help.

I have updated the post now

Thank you

1 Like