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

Thursday, June 23, 2011

GATE 2011 C Progamming Question

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

Consider the following recursive function that takes two arguments

unsigned int foo(unsigned int n, unsigned int r)  {
  if(n > 0) return ((n % r) + foo(n / r, r));
  else return 0;
}


What is the return value of the function "foo" when it is called as foo(345, 10)?

(A) 345
(B) 12
(C) 5
(D) 3

Answer: (B) 12
5 + 4 + 3 + 0 = 12

What is the return value of the function "foo" when it is called as foo(513, 2)?

(A) 9
(B) 8
(C) 5
(D) 2

Answer: (D) 2
1 + 1 = 2
Written by