What variable am I not using?

Tell us what’s happening:
Hi, as far as I know i did the process right, but I was told I am adding the wrong variable. I see no other variables here unless I am missing something.

  **Your code so far**

function sum(arr, n) {
// Only change code below this line
if (n <= 1) {
return 0;
} else if (n >= 2) {
return sum(arr, n) + n ;
}
// Only change code above this line
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

Hint 1: When using recursion, each recursive call should get you closer to the base case. Your base case currently checks if n <= 1 so each time you call sum the value you are passing in for n should get closer to 1.

Hint 2: You are adding the numbers in the array, not the counter n.

Also, I would rethink your base case a little. When do you want to stop the recursion? If n is 1 do you really want to return 0?

1 Like

You are adding the first n elements of arr. So, if arr is [3, 8, 4, 9, 2, 6] and n is 3, then the function returns 15 (the first 3 elements of arr, so 3 + 8 + 4 = 15).

The recursive call should be something like

(get the sum of first 2 elements) + 3rd element of arr

The recursive call for the (get the sum of first 2 elements will be

(get the sum of first 1 element) + 2nd element of arr

Then

(get the sum of first 0 element) + 1st element of arr

(get the sum of first 0 element) is the end case of the recursion. You return 0.

Graphically it looks like this
sum

A recursive function must have an end condition from where the recursion loop will get out, what you don’t have in your code. This will lead to an infinite loop. first, try to add an end condition.

function sum(arr, n) {
      if(n <= 0){
        return n;
      }else{
        return arr[n -1] += sum(arr, n-1)
      }
}

Try to understand the code and for a visual execution paste your code here and look how the code is executed: JSVisual

I don’t think you should be using +=. You don’t want to change the content of the array.

1 Like

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