Sunday, July 3, 2011

GATE 2010 C Programming Question

GATE 2013 Comprehensive Information Pagehttp://www.codeblocks.info/2012/08/gate-2013.html

What is the value printed by the following C 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()
{
  int a[] = {12, 7, 13, 4, 11, 6};
  printf("%d", f(a, 6));
  return 0;
}



(A) -9
(B) 5
(C) 15
(D) 19

Answer
------
(C) 15

Explanation
-----------
f(12,....6, 6) = 12 + f(7,....6, 5)
f(7,....6, 5) = 7 - f(13,....6, 4)
f(13,....6, 4) = 13 - f(4,....6, 3)
f(4,....6, 3) = 4 + f(11,....6, 2)
f(11,....6, 2) = 11 - f(6, 1)
f(6, 1) = 6 + f(NULL, 0)
f(NULL, 0) = 0

Hence, 12 + (7 - (13 - (4 + (11 - (6 + (0)))))) = 15
Written by