I really have no idea how to solve this problem, can someone help me pls? Basic JavaScript: Replace Loops using Recursion

Example: ```
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}


Challenge: 

Write a recursive function, sum(arr, n), that returns the sum of the first n elements of an array arr.

function sum(arr, n) {
  // Only change code below this line

  // Only change code above this line
}





Output should look like this:

sum([1], 0) should equal 0.
sum([2, 3, 4], 1) should equal 2.
sum([2, 3, 4, 5], 3) should equal 9.
Passed
Your code should not rely on any kind of loops (for or while or higher order functions such as forEach, map, filter, or reduce.).
You should use recursion to solve this problem.

Link to challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion

bro, can you help me solve the problem?

So you need to think about what to increment/decrement, and at what point you need to stop incrementing/decrementing.

When the function is first called it’s given n, which is the amount of elements to sum up from the front of the array.

If this were a for loop I’d maybe solve it like this:

function sum(arr, n) {
  let sum = 0;
  for (let i = n - 1; i >=0; i--) {
    sum += arr[i];
  }
}

So if it were a for loop, our base case (where the loop stops) would be at i === 0, which correlates to n === 1.

Hope this gives you some direction.

And here’s a good article about recursion:

1 Like

guys its like this and let me explain it:

function sum(arr, n) {

  // Only change code below this line

  if (n <= 0)// if n is less than or equals to 0{

    return 0 // should return zero

  } else {

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

  }

  // Only change code above this line

}

sum([1],0);

@nathanielavila10 It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.