What does -1 in recursion mean?
P粉578343994
P粉578343994 2023-09-07 10:10:20
0
1
661

In this code, I'm trying to understand the concept of recursion, but I'm completely missing the point: sum(arr, n) = sum(arr, n - 1) arr[n - 1];

I have this code:

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'm trying to understand the expression: sum(arr, n - 1) arr[n - 1]; Is this the case: In sum(arr, n - 1), whether n is (index - 1) or (n - 1) is the length of the array item to be added. Also, after doing this, what about the second expression arr[n - 1]. Is [n- 1] an array element? Because it is in an array, there is "[]".

Sorry if anything is stupid or annoying, but if anyone can help point me in the right direction I'd be very grateful.

P粉578343994
P粉578343994

reply all(1)
P粉423694341

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

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

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

The only case where this rule does not apply is when n<=0, in which case the sum is 0.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template