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.
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.