Recursion
![Question 35, GATE 2010: What value does this C program print?
#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; }
Options: (A) −9; (B) 5; (C) 15; (D) 19.](../../assets/questions/CS-2010-Q45-1.webp)
Answer & solution
Answer: C (no official key was published)
Step through it (17 steps)
Evaluate from the last array element backward. The empty suffix returns 0; f([6])=6; f([11,6])=11−6=5; f([4,11,6])=4+5=9; f([13,4,11,6])=13−9=4; f([7,13,4,11,6])=7−4=3; finally 12+3=15. The function tests each current element’s parity, not its index. Printed value 15, C.
The recurrence is not a flat alternating sum of the original elements: subtraction applies to the entire recursively computed suffix. Parentheses make the evaluation explicit: 12+(7−(13−(4+(11−6))))=15. Pointer arithmetic a+1 advances to the next integer and n−1 shrinks the remaining array; the parity test examines the value *a at each call.