Solution so I can move on please!

Hi, I have been struggling with this problem for 2 days now, and I just want to see the solution so I can learn what I am missing. The recursion is very hard for me to understand.

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 13310.76.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.108 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

1 Like

Welcome to the community!

Sorry to hear that you’ve been struggling with this. If you click on “Get Help” then “Get a Hint”, you’ll be taken to a post with hints + possible solutions. You can find a solution there to help guide and direct you for this particular challenge.

For your ease, this is the page: freeCodeCamp Challenge Guide: Replace Loops using Recursion

1 Like

Ah, yes. I’ve seen this solution, but thanks for the reference! The problem with the given solution is giving me an error for these things `

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

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

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

I’m not sure what I’m supposed to do or what to add to the problem in order to move forward.

4 Likes

Hello and welcome to the freeCodeCamp community~!

I ran the solution from the guide post @darren-stoll linked for you against the tests in the challenge, and everything passes on my end. The solution appears to be correct. Can you share your current code again?

Hi, thank you all for the welcome! I deleted the comment codes and it worked. Thank you again.

1 Like

I am glad you were able to solve it! I do, however, strongly encourage that you spend the time to understand recursion. It’s a powerful tool to have in your kit. :slight_smile:

3 Likes

if you reall just want to move one, just go to the lists of challenges and select the next challenge - challenges are not mandatory for the cert

your issue is that you have the call sum[n-1] which is not the correct way to call a function plus you are not doing anything with it

1 Like

Hey @rylidavis94!

First off, I am glad that you were able to figure out the solution. I do agree with @nhcarrigan’s advice about spending extra time on this topic because it will come up again later on in the javascript section.

This is a helpful video explaining how recursion works and what is actually happening inside the computer.

I would also highly suggest that you watch Colt’s other video on call stacks as well

Hope that helps!

Happy coding!

21 Likes

That first video really REALLY helped me understand what was happening! Thank you so much. I did not realize that all of these returns were pending until the base case was hit. I made this account just to express my gratitude. I passed the challenge just fine but did not really grok what was going on.

5 Likes