Recursion challenge

I’m stuck on this challenge:
Write a recursive function, sum(arr, n) , that returns the sum of the first n elements of an array arr .

I need to achieve this:

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

My code so far:


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

if (n <= 0) {
return 0;
} else if (n > 0) {
return 2;
}else if(n < 9) {

 return 9;
 }else {
return sum(arr, n - 1) * arr[n - 1];
}

 // Only change code above this line
}

Challenge: Replace Loops using Recursion

Link to the challenge:

If n is not less or equal 0, then it’s definitely greater than 0 and therefore such function will always return 2 for any positive number n

I think seeing it this way might help you out:
0 1 2 3 4 5
-1 0 1 2 3 4
The starting number the -1 is actually a 0 as we needed to do a negative count

Hello,

I see that you don’t understand the definition of “recursion”, but that is totally fine. :slight_smile:

Recursion :
(1) it’s a recursive function calls itself.
example: function countdown(num){ …countdown(num-1);}
(2) it’s recursive function that needs 2 main paths.
-(a) a base case: a terminating condition
-(b) a recursive part: the main part

So with this question, let’s find the base case first

function sum(arr, n) {
  if(n <= 0) {  //This is the base case, n needs to be greater than 0
    return 0;  //So when n is no longer greater than 0, please terminate it and return 0.
  } else {
    /*Now, let's write the recursive part! 
      But first thing first, We need to know that computer counts array from 0. 
      Therefore, when n=3 means that we count the index of array till  (3-1). 
      Here we start with  the first one arr[n-1] , and then we can call the function itself sum(arr, n-1). Continue repeating it till the base case happens.
      The result will be arr[n-1] + arr[n-1-1]+ arr[n-1-1-....]+ arr[n-n]*/
    return arr[n - 1] + sum(arr, n - 1) ; 
  }
}

Thank you for your explanation! Makes sommuch more sense now😊

But still, a simple question like this better use for loop. :wink: