function sum(arr, n) {
if(n<=0){return 0}
else {
return sum(arr, n-1) + arr[n-1]
}
}
HI, i can’t understand the last step,
up to here there are: sum(arr,
but then why
n-1 ) + arr[n-1]
thanks in advance for the answer
S.
function sum(arr, n) {
if(n<=0){return 0}
else {
return sum(arr, n-1) + arr[n-1]
}
}
HI, i can’t understand the last step,
up to here there are: sum(arr,
but then why
n-1 ) + arr[n-1]
thanks in advance for the answer
S.
Use real numbers. What if I gave you:
sum([7,8], 2);
What will the return
statement be on the initial function call. Replace all the variable names with their correct numeric/array values.
return sum(arr, n-1) + arr[n-1]
return sum(arr,1)+arr[1]
or?
return sum(arr,1)+arr[0]
I still do not understand…
There is no need for guessing here. You wrote the function so you should know exactly what the values are
If 2
is passed in as the second argument then n
will equal 2
inside the function. So arr[n-1]
will be arr[1]
. But what is the actual value of arr[1]
? If the array being passed in is [7, 8]
, then arr
equals [7, 8
] inside the function. So what would arr[1]
be?
Keep going, rewrite return sum(arr,1)+arr[1]
by replacing the variables arr
and arr[1]
with their actual values based on what was passed into the function.
let arr=[7,8];
arr[1] is 8
return sum(arr,1)+8
sum([7,8],1) how does this block work?
essentially, one number is added at a time sum(arr,n-1) where n-1 is just used to decrease the number in the arr to add, and arr[n-1] is the number to add what?
Wel, what would happen if you make that function call?
From what i understand, n-1 in sum(arr, n-1) indicates how many values are gonna be summed from arr…n-1 = 1 in this case so it’s gonna take the first value of arr, that is 7…arr[1] = 8, so 7+8 =15…if arr was e.g [7, 8, 9] and n was 3 then sum([7,8,9], 2) would be 15 and arr[2] would be 9 so 15 + 9 = 24
console.log(sum(arr,1)); //7
console.log(arr[2-1]); //8
in the second case I understand why it is worth 8 in the first it is not…
What’s the sum of the first 1 numbers in arr?
the first time the sum is 8 and on the second recall the sum becomes +7 ?
because n becomes 1 and 1-1=0 the first element of the array
so arr[n - 1] is used only because in js we start counting from 0 and we pass the number of parameters starting from 1