Open In App

GATE | GATE-CS-2004 | Question 31

Like Article
Like
Save
Share
Report

Consider the following C function: 

C




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)

Explanation:

Let’s understand the problem with given Dry Run:

Initially, the static variable i is initialized to 1.

f(1) is called:

  • n is 1, which is less than 5.
  • n is updated to n + i, which becomes 2.
  • i is incremented to 2.
  • The function calls itself recursively with the updated value of n, so it becomes f(2).

f(2) is called:

  • n is 2, which is less than 5.
  • n is updated to n + i, which becomes 4.
  • i is incremented to 3.
  • The function calls itself recursively with the updated value of n, so it becomes f(4).

f(4) is called:

  • n is 4, which is less than 5.
  • n is updated to n + i, which becomes 7.
  • i is incremented to 4.
  • The function calls itself recursively with the updated value of n, so it becomes f(7).

f(7) is called:

  • n is 7, which is greater than or equal to 5.
  • The function returns n which is 7.

Now, the recursive calls start to end:

  • The return value from f(7) was 7, and this is returned as is to the previous call, f(4).
  • The return value from f(4) was 7 (the result from f(7)), and this is returned as is to the previous call, f(2).
  • The return value from f(2) was 7 (the result from f(4)), and this is returned as is to the first call, f(1).

So, the value returned by f(1) is 7.

Hence (C) is the correct answer.


Quiz of this Question
Please comment below if you find anything wrong in the above post


Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads