Consider the following C function, what is the output? #include <stdio.h> int…

2007

Consider the following C function, what is the output?

#include <stdio.h>
int f(int n)
{
    static int r = 0;
    if (n <= 0) return 1;
    if (n > 3)
    {
        r = n;
        return f(n-2)+2;
    }
    return f(n-1)+r;
}

int main()
{
    printf("%d", f(5));
}

  1. A.

    5

  2. B.

    7

  3. C.

    9

  4. D.

    18

Attempted by 161 students.

Show answer & explanation

Correct answer: D

Key insight: the static variable r retains its value across recursive calls and is updated when n > 3.

  • Call f(5): since 5 > 3, r is set to 5 and the function returns f(3) + 2.

  • Call f(3): 3 is not > 3, so it returns f(2) + r. At this point r = 5.

  • Call f(2): returns f(1) + r (r = 5).

  • Call f(1): returns f(0) + r. f(0) is the base case and returns 1, so f(1) = 1 + 5 = 6.

  • Back up: f(2) = f(1) + r = 6 + 5 = 11; f(3) = f(2) + r = 11 + 5 = 16.

  • Finally, f(5) = f(3) + 2 = 16 + 2 = 18.

Therefore the program prints 18.

Explore the full course: Gate Guidance By Sanchit Sir