### Recursion problem solution not clear

 ``123456789101112131415161718192021`` ``````Hi every one, please any one can explain following program output . #include int func(int *a, int n) { if(n ==0) return 0; else if(*a %2 == 0) return *a+func(a+1, n-1); else return *a-func(a+1, n-1); int main() { int a[] ={ 12, 7, 13,4,11,6}; printf(" = %d \n", func(a,6)); return; } output is : 15 but it is not clear for me how ?pls can any one explain in steps.``````
Last edited on
1) func(a,6) calls func pointing to '12', indicating there are 6 elements in the array.

2) func looks at 12, sees that it is even, and therefore does *a+func(a+1, n-1), which sums 12 with the result of the next call to func

3) next call to func is effectively `func(a+1,5)` which points to the '7'. func sees this is odd, so it subtracts `7-func( ...next call... )`

4) next call is effectively `func(a+2,4)` which points to the '13'. Again this is odd, so it subtracts `15-func( ...next... )`

5) next points to 4, which is even... so [code]4+func(...next...)

6) next points to 11, which is odd... so it subtracts

7) next points to 6, which is even... so it adds

8) next call has n=0, so func just returns 0

9) Step 7's call (6,even) takes the return value of 0, adds 6 to it, then returns 6

10) Step 6's call (11,odd) takes that return value of 6, subtracts it from 11, and returns 5 (11-6)

11) Step 5's call (4,even) takes that return value of 5, add's 4 to it... returning 9

12) Step 4's call (13,odd) does 13-9, returning 4

13) Step 3's call (7, odd) does 7-4, returning 3

14) Step 2's call (12,even) does 12+3, returning 15

15) Step 1 gets the final return value of 15 and prints it. Hence why your program outputs 15
Topic archived. No new replies allowed.