JavaScript Algorithms and Data Structures part 2

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

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

  return sum(arr, n - 1) * arr[n + 1];
}
// Only change code above this line
}
// sum([1,3],5)
console.log(sum([2, 3, 4], 1))
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36

Challenge: Replace Loops using Recursion

Link to the challenge:

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

You’re getting close but you have a few issues:

  • For your base case, think about what number you want to return. If I called your function as sum([1,2,3], 0) that means that I want to return the sum of the first 0 elements in the array, or otherwise, the sum of none of the elements. If you aren’t summing up any elements, what do you think a good return value would be?

  • Remember, this is the sum of the elements. Should you really be multiplying them when you hit the else and make the recursive call?

There is one more issue after the two above. Think about what the value of n is when you are accessing a value from the array.

can you calibrate more on that

sum means add. You should add the array elements together.

how can i do that please :pray:

I’m going to take a wild guess here and assume you know how to add two numbers together in JS? Remember, the function sum always returns a number. So you can add a number to whatever the recursive call to sum returns.

There is not much difference here between the multiply function in the example and the sum function you are trying to implement.

1 Like

i still dont understand

You need to be very specific about what you don’t understand. We don’t know what you don’t understand.

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

What part of that don’t you understand? Did you study the instructions and example? As I mentioned, the example is basically the same thing as what you are asked to do with sum.

Please do not just keep repeating that you don’t understand. We need to know exactly what you don’t understand so we know how to help you. I fear I will grow tired of trying to help you if you don’t give me something more to go on.

1 Like

its fine my problem is solved

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.