This is simple recursion, and best visualized with pen and paper. When you give the function sum
an array arr
, and the array length n
, unless you have reached the beginning of the array index, sum(arr,n-1)+arr[n-1]
is returned, meaning:
- the function
sum
calls itself (recursion), but passes in a different index n
, this function call eventually returns a value.
- to the recursive call,
sum
adds the value of arr[n-1]
let us try with a test case of arr=[1,2,3,4,5] and n=5.
1st call to sum
, return sum(arr,4)+arr[4],
2nd, return sum(arr,3)+arr[3],
3rd, return sum(arr,2)+arr[2],
4th, return sum(arr,1)+arr[1],
5th, return sum(arr,0)+arr[0],
6th, return 0 (since n<=0)
Then the last result of 6th call is added to each of the previous returns.
5th, return 0+1=1,
4th, return 1+2=3,
3rd, return 3+3=6,
2nd, return 6+4=10,
1st (the original call to sum
) finally get 10+5=15.
Therefore running sum([1,2,3,4,5],5) returns 15, and the functionsum
adds up the values within the passed array backwards from the index passed in.