That’s actually a very interesting question. Let’s try plugging those numbers in. It’s sort of like a piecewise function in math if it helps.
The first example:
Summary
that one has an value of 0 for the variable of n
. In the first if statement, we check to see if n
is less than or equal to zero. If it is, we return the value of n.
The second example:
Summary
This one has a value of 1 for the variable of n
and [2,3,4] for the arr
variable. As n is greater than 0, we return the value of the sum of everything else we have and the last value in the array.
return sum( [2,3,4], 1-1)+arr[1-1];
Or simplified
return sum( [2,3,4], 0)+arr[0];
sum( [2,3,4], 0)
returns 0 as established earlier and the value at index 0
is 2.
The third example:
Summary
This one has a value of 3 for the variable of n
and [2,3,4,5] for the arr
variable.As n is greater than 0, we return the value of the sum of everything else we have and the last value in the array like last time.
Here’s what we get if we plug the numbers in.
return sum( [2,3,4,5], 3-1)+arr[3-1];
return sum( [2,3,4,5],2)+arr[2];
sum( [2,3,4,5],2)
calls the function again which will return sum( [2,3,4,5],2 - 1) + arr[1 - 1]
which will then return sum( [2,3,4,5],1 - 1) + arr[0]
. Thus adding it all up.
Here it is written out.
With arr = [2,3,4,5]
sum(arr, 3)
= sum(arr, 2)
+ arr[2]
sum(arr, 2)
= sum(arr,1)
+ arr[1]
sum(arr,1)
= sum(arr,0)
+ arr[0]
sum(arr,0)
= 0
With a bit of substitution that leads to:
sum(arr, 3)
= arr[2]
+ arr[1]
+ arr[0]`
or
sum[2, 3, 4, 5], 3)
= 4 + 3 + 2
And solving this gives us:
sum[2, 3, 4, 5], 3)
= 9
Happy learning. 