Hi @ilenia…I’m going to try!
function sum(arr, n) {
if n<=0 {
return 0;
} else {
return sum(arr, n-1) + arr[n-1];
}
}
for the base case, where n<=0, it returns 0 - so whenever n gets to this point, it returns zero and stops.
for larger values of n (that is, greater than or equal to 1) the function calls itself but with n-1 and it will keep doing this until n is equal to or less than zero.
so…
sum ([2,3,4,5] , 3) //
n here is ‘3’ so does not meet the if statement and goes straight into the condition where it starts to recurse itself
sum([2,3,4,5] , 2) + 2 // i.e. "sum([2,3,4,5], n-1) + sum[n-1] ";
here the first part is looking for the sum of the first 2 elements of the array (which equals 5) and the second part it calls itself but as [n-1] (ie [3-1] ) which equals 2…thus result here so far is 5 + 2 = 7
then it continues to call itself
(sum([2,3,4,5] , 1) + 1) + 2 // here it is looking for the ‘sum’ of the first element in the array (which equals 2) , then adds the previous two results (ie the +1 and +2)
result here is 2 + 7 = 9
and it still continues to recurse itself…
(sum(([2,3,4,5],0) +0) + 1) + 2 // here n is equal to 0 so this will automatically return a 0 as it meets the first if statement…so here, it stops as it has reached the base case.
thus, the total (final result) is 7 + 2 + 0 = 9
is that right?
this explanation doesn’t fit with @sitek94 though so I’m guessing I’ve just somehow made it fit without really understanding what’s happening
with this explanation it appears (to me) that the ‘n’ value in the function’s parenthesis is selecting the relevant index of the array in that parenthesis:
sum( [1,2,3] , 2). //result is 2. (because n=2 and is choosing the 2nd index, which is 2)
sum( [1,2,3], 1) + 2. //result is 1 + 2. (because n=1 and is choosing the 1st index)
sum( ([1,2,3],0) +1) +2. //result is 0 + 1 + 2. (because n=0, it automatically returns 0)
thus 0 + 1 + 2 = 3.
if I apply that logic to the other function:
sum( [2,3,4,5], 3) //result is 4 (because n = 3 and is choosing the 3rd index, which is 4)
sum( [2,3,4,5], 2) + 2 //result is 3 + 4. (because n = 2 and is choosing the 2nd index, ie 3)
sum (( [2,3,4,5], 1) + 1) + 2 //result is 2 + 3 + 4
sum ((( [2,3,4,5], 0) + 1) + 1) + 2. //result is 0 + 2 + 3 + 4
final result /total = 9
same result either way but I don’t know which is the correct logic!
I’ve tried researching online but I’m feeling confused…
I hope how I’ve explained my process makes sense
would love some feedback from anyone who happens to read this reply