skip to Main Content

In this code block, am trying to understand the concept of recursion but, where I miss the whole point is this: sum(arr, n) = sum(arr, n - 1) + arr[n - 1];

I have this code block:

function sum(arr, n){

  if(n <= 0){
    return 0;

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

}

console.log(sum([5, 4, 7, 9, 2, 6], 5); 

I am trying to understand the expression: sum(arr, n - 1) + arr[n - 1];
is it that in: sum(arr, n - 1), n is the (index – 1) OR (n – 1) is the length of array items it is going to add. Also, after this is done, what about the second expression arr[n – 1]. is [n- 1] an array element since it’s in an array hence the "[]".

I apologize if any of this is silly or annoying but, i would really appreciate if someone could help point me in the right direction.

3

Answers


  1. Your function sum(arr,n) could be described as computing arr[0]+...+arr[n-1].

    Which is equivalent to arr[0]+...+arr[n-2]+arr[n-1]

    Which is equivalent to sum(arr,n-1) + arr[n-1]

    The only time this doesn’t apply is when n<=0, in which case the sum is 0.

    Login or Signup to reply.
  2. JavaScript arrays and other indexed variables are always zero-based, so the first element is index #0 whereas the length of the array is last index + 1.

    See it here…

    var A=['a','b','c','d']; // <--- the "n" here is 4 but the last item is index 3
    

    There are four elements so the array lengthy is 4 but the last element’s index number is 3 since the index goes…. [ 0, 1, 2, 3 ] !

    Hence the n-1 used so that the loop’s counter won’t run past the index of elements.

    Login or Signup to reply.
  3. When you have a recursive function you need to end the cycle somehow, otherwise the circle will continue and will consume all your memory, so paid attention to the if

    if(n <= 0)
    
    return 0
    

    This condition wen n <= 0 end the cycle and return 0, so if you never make n <= 0 the cycle never end, then you have the implement a logic to do it sum(arr, n – 1), you then subtract -1 from n ultin it is 0 and the cycle end that means that line

    Example

    sum(arr, 4 - 1)
    sum(arr, 3 - 1)
    sum(arr, 2 - 1)
    sum(arr, 1 - 1)
    
    0
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search