What is the output of the following program ? #include <stdio.h> int f (int…
2026
What is the output of the following program ?
#include <stdio.h>
int f (int *a, int n)
{
if(n<=0) return 0;
else if (*a%2 == 0) return *a + f(a+1, n-1);
else return *a - f(a+1, n-1);
}
int main(void)
{
int a[] = {12, 7, 13, 4, 11, 6};
printf("%d", f(a,6));
return 0;
}- A.
-9
- B.
5
- C.
15
- D.
19
Attempted by 134 students.
Show answer & explanation
Correct answer: C
Concept
This is non-tail recursion: each call has a pending add or subtract that runs AFTER the recursive call beneath it returns. The rule per element is: if the element is even, return element + (recursive result of the rest); if odd, return element - (recursive result of the rest); the base case (n<=0) returns 0. Because the recursive result is nested inside the next sign, the signs do NOT distribute independently over the elements - they compound as the stack unwinds.
Why naive parity-sum fails
It is tempting to just add every even element and subtract every odd element: (12+4+6) - (7+13+11) = 22 - 31 = -9. That is wrong, because the subtraction applies to the WHOLE remaining recursive result, not to a single element. The correct evaluation must unwind from the deepest call outward.
Trace (deepest call first)
f(a+6, 0): base case, returns 0.
f(a+5, 1): element 6 is even -> 6 + 0 = 6.
f(a+4, 2): element 11 is odd -> 11 - 6 = 5.
f(a+3, 3): element 4 is even -> 4 + 5 = 9.
f(a+2, 4): element 13 is odd -> 13 - 9 = 4.
f(a+1, 5): element 7 is odd -> 7 - 4 = 3.
f(a, 6): element 12 is even -> 12 + 3 = 15.
Cross-check
Expand the nesting in one line: 12 + (7 - (13 - (4 + (11 - (6 + 0))))) = 12 + (7 - (13 - (4 + (11 - 6)))) = 12 + (7 - (13 - (4 + 5))) = 12 + (7 - (13 - 9)) = 12 + (7 - 4) = 12 + 3 = 15. The program prints 15.