What will be the output of the following C code? #include<stdio.h> int fun(int…

20232023

What will be the output of the following C code?

#include<stdio.h>
int fun(int x, int y);
int main()
{
    int i,n;
    i=5;
    n=7;
    int f = fun(5,7);
    printf("%d", f);
}
int fun(int x, int y)
{
    if(x<=0)
        return y;
    else
        return(fun(x-1,y-1));
}
  1. A.

    0

  2. B.

    1

  3. C.

    2

  4. D.

    3

Show answer & explanation

Correct answer: C

Concept: in a recursive function that only does "return recursiveCall(...)" in its recursive branch (a tail-recursive pattern), the value produced by the base case travels back up unchanged through every pending call. So the final result equals whatever the base case returns, not the parameter value that made the recursion stop.

Application: trace the calls made by fun(5, 7):

  1. fun(5, 7): x = 5, so the condition x <= 0 is false; it calls fun(4, 6).

  2. fun(4, 6): x = 4, condition false; it calls fun(3, 5).

  3. fun(3, 5): x = 3, condition false; it calls fun(2, 4).

  4. fun(2, 4): x = 2, condition false; it calls fun(1, 3).

  5. fun(1, 3): x = 1, condition false; it calls fun(0, 2).

  6. fun(0, 2): x = 0, so the condition x <= 0 is true; the base case returns y, which is 2.

Each of the five pending calls simply passes this same value upward without changing it, so fun(5, 7) evaluates to 2, and that is what main() prints.

Cross-check: after n recursive calls, both x and y have each decreased by n from their starting values 5 and 7. The base case first fires at the smallest n for which 5 - n <= 0, which is n = 5; at that point y = 7 - 5 = 2, confirming the traced result independently.

Explore the full course: Cocubes Preparation