# Lesson "Replace Loops with Recursion"

I managed to get the answer using the two hints , but that still hasn’t helped me to understand how to function worked. I understand the concept of recursion and that it’s calling itself again, but what I don’t understand is how the elements in the array are being added up. If anyone could help me to understand, I’d really appreciate it <3

freeCodeCamp Challenge Guide: Replace Loops using Recursion

3 Likes

Recursion is a very confusing topic. If you search the forum, you’ll find a lot of detailed explanations and discussions. I would recommend starting by checking out several of those. If you’re still confused, come back and explain what is still holding you up.

1 Like

Also, please don’t post pictures of code. Please just cut and paste it in and use markdown formatting.

No, no problem. Let us know if you are still stuck after some reading.

I’m currently working on this one too and I think I finally get it-- The thing that wasn’t clear for me was that n stands for an index of the array.

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 in:

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

//we would usually start at index 3, but the function states that (n-1) is the starting index, so n = 2 (the value 4 is at index 2) . We then find the sum of the array up to index 2. (2+3+4) = 9

For the example :

sum([2,3,4], 1) // we’d normally start at index 1, but since n=(n-1), we find the sum of the array up to index 0, which is 2.

I hope this makes a little sense – and I hope someone will confirm I’m correct lol

3 Likes

You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with `[spoiler]` and `[/spoiler]` tags on the line above and below your solution code.