Output of following program? #include <stdio.h> int fun(int n, int *f_p) { int…

2009

Output of following program? 

#include <stdio.h>
int fun(int n, int *f_p)
{
    int t, f;
    if (n <= 1)
    {
        *f_p = 1;
        return 1;
    }
    t = fun(n- 1,f_p);
    f = t+ * f_p;
    *f_p = t;
    return f;
}

int main()
{
    int x = 15;
    printf (" %d \\n", fun(5, &x));
    return 0;
}

  1. A.

    6

  2. B.

    8

  3. C.

    14

  4. D.

    15

Attempted by 17 students.

Show answer & explanation

Correct answer: B

Answer: 8

Key insight: the function computes Fibonacci-like values with the pointer argument holding the previous Fibonacci number during unwinding.

  • n = 1: function returns 1 and sets the pointed value to 1.

  • n = 2: t = 1, f = t + pointed = 1 + 1 = 2, pointed becomes 1, return 2.

  • n = 3: t = 2, f = 2 + 1 = 3, pointed becomes 2, return 3.

  • n = 4: t = 3, f = 3 + 2 = 5, pointed becomes 3, return 5.

  • n = 5: t = 5, f = 5 + 3 = 8, pointed becomes 5, return 8.

Therefore the call fun(5, &x) returns 8. Note: the variable passed by pointer is updated during recursion and ends as 5 after the call, but the printed value is the function's return value 8.

Explore the full course: Gate Guidance By Sanchit Sir