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粉4236943412023-09-08 09:29:40
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.