When dealing with recursive functions, they usually work with an immediately accessible value and another value obtained by calling themselves until a base case is met.
In this scenario, the accessible parameter is a number from an array and the operation simply involves addition. The function reaches the base case when its parameters satisfy the conditions set in the code.
To grasp how the final result is achieved, consider the various iterations that occur:
- During the first iteration, sum([10,20,30,40], 3)
The condition in the code is not met because 3 (n) is greater than 0, triggering execution of the else branch's code.
We now have sum([10,20,30,40], 2) + arr[2]. While we do not yet know the outcome of the recursive call, we have the value of the number at the third position in the array, which is 30 (arrays typically start from 0).
- Moving onto the second iteration, sum([10,20,30,40], 2)
Once again, this does not satisfy the base case yet, leading to:
sum([10,20,30,40], 2-1) + arr[2-1] ->
sum([10,20,30,40], 1) + arr[1] ->
sum([10,20,30,40], 1) + 20
- Continuing to the third iteration, sum([10,20,30,40], 1)
At this point, we have partial results of 30 and 20. These values, along with other iteration outcomes, are all added together due to the nature of the code within the else branch—simple addition.
sum([10,20,30,40], 1-1) + arr[1-1] ->
sum([10,20,30,40], 0) + arr[0] ->
sum([10,20,30,40], 0) + 10
Another partial result of 10 has been accounted for.
- Lastly, the fourth and final iteration arrives, sum([10,20,30,40], 0)
Finally reaching the base case, the code executes the logic within the if branch, halting further recursion as there are no additional calls within the code. The result of sum([10,20,30,40], 0) equates to 0.
Looking back on the iterations:
• Third iteration: sum([10,20,30,40], 0) + 10 resolved to 10.
• Second iteration: sum([10,20,30,40], 1) + 20 yielded 30.
• First and initial call to the function: sum([10,20,30,40], 2) + 30 resulted in 60.
While recursive functions may seem intricate initially, grasping the concept of accumulating partial results until reaching the base case will make it easier. Patience is key to understanding this concept.