Saturday, 25 February 2017

GATE EXAM PREPARATION IN "C" - C function(GATE CS 2004)

Consider the following C function:
int f(int n)
{
   static int i = 1;
   if (n >= 5)
      return n;
   n = n+i;
   i++;
   return f(n);
}
The value returned by f(1) is 
a) 5
b) 6
c) 7
d) 8
Answer (c)
Since i is static, first line of f() is executed only once.
Execution of f(1) 
    i = 1
    n = 2
    i = 2
 Call f(2) 
    i = 2
    n = 4
    i = 3
 Call f(4) 
   i = 3
   n = 7
   i = 4
 Call f(7)
  since n >= 5 return n(7)

No comments:

Post a Comment