hi!
Can someone help me with this code please? I don’t undestand how it works:
Write a recursive function, sum(arr, n)
, that returns the sum of the first n
elements of an array arr
.
function sum(arr, n) {
if(n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
I know this is the answer, but I can notunderstand the way of testing it.
sum([2, 3, 4, 5], 3)
should equal 9.
sum([2, 3, 4], 1)
should equal 2.
sum([1], 0)
should equal 0.
Thank you in advance!