Here's another e.g. to hopefully clarify recursion:
let's say function that sums the first
n elems in an array:
1 2 3 4 5 6 7 8 9 10 11
|
int sum( int *arr, int n )
{
int sum;
if ( n == 0 )
return 0;
else
{
sum= sum( arr, n - 1 ); // line A
return sum + arr[ n - 1 ]; // line B
}
}
|
1 2 3 4 5
|
int main()
{
int list[] = {2,4,6};
cout << sum(list, 3);
}
|
Winding process: (bottom of stack is leftmost function)
==================================
0)Main function initially calls sum
(stack bottom)main->sum(arr, 3)(stack top)
1)3 != 0, so run else so n = 2
main -> sum(arr, 3) -> sum(arr, 2)
2)we call function sum again and now 2 passed and 2 != 0 so run else with n = 1
main -> sum(arr, 3) -> sum(arr, 2) -> sum(arr, 1)
3)we call funciton sum again, and 1 != 0 so run else with n = 0
main -> sum(arr, 3) -> sum(arr, 2) -> sum(arr, 1) -> sum(arr, 0)
Unwinding process:
==============
main -> sum(arr, 3) -> sum(arr, 2) -> sum(arr, 1)
1) so n == 0 now so we return 0 to caller sum
(line A)(pop sum(arr, 0) off stack and int sum = 0, then we run
line B so total + arr[1-1] since top of stack is sum(arr, 1) and pop this off stack so index 0 so we return 0 + element at index 0:2 so we return 2 to caller which is function sum.
main -> sum(arr, 3) -> sum(arr, 2)
2) so we go back to
line A, and now int sum = 2. Now we run
line B
which is 2 + arr[2 - 1] so index 1 since stack top is sum(arr, 2 ) where n = 2
so what we return is: 2 + 4 = 6 so we return 6 to caller: sum and pop off sum(arr, 2)
main -> sum(arr, 3)
3) we go back to
line A, and int sum = 6. Then we go to
line B, so
6(current value of sum) and add to arr[3 - 1] so index 2 (since n = 3, since current top o stack is sum(arr, n = 3) so the sum is: 6 + 6 = 12 and we return to caller: main and pop off sum(arr, 3).
4) 12 returned to function: main and main popped off by whoever called it, program terminates!