GATE 2010 CS (CS1) – Question 45
What 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;
}Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (C) 15
Explanation
Evaluate from the last element backwards. The empty suffix returns zero; then f([6])=6, f([11,6])=11−6=5, f([4,11,6])=4+5=9, f([13,…])=13−9=4, f([7,…])=7−4=3, and the full call returns 12+3=15. The parity tested is the element, not the remaining length. Thus C.