Question

Consider the C functions foo and bar given below:

int foo(int val) {
    int x = 0;
    while (val > 0) {
        x = x + foo(val--);
    }
    return val;
}

int bar(int val) {
    int x = 0;
    while (val > 0) {
        x = x + bar(val - 1);
    }
    return val;
}

Invocations of foo(3) and bar(3) will result in:

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2017 answer key

Solution

Trace both functions for parameter value 3 to detect whether recursion terminates or causes stack overflow/infinite looping.

Examine function foo(3):

int foo(int val) {
    int x = 0;
    while (val > 0) {
        x = x + foo(val--);
    }
    return val;
}

In the call foo(3), the loop condition val > 0 (3>03 > 0) is true. The expression foo(val--) evaluates the postfix decrement: the argument passed to foo is the current value 3, and val is decremented to 2. The new call foo(3) executes with argument 3, which in turn calls foo(3) again recursively. This results in unbounded recursive calls with no base case, exhausting the call stack and leading to stack overflow (abnormal termination).

Examine function bar(3):

int bar(int val) {
    int x = 0;
    while (val > 0) {
        x = x + bar(val - 1);
    }
    return val;
}

In the call bar(3):

  • val = 3 > 0: calls bar(2). In bar(2), val = 2 > 0: calls bar(1). In bar(1), val = 1 > 0: calls bar(0).
  • In bar(0), val > 0 is false (0>00 > 0 is false), so bar(0) immediately returns 0 without further recursion.
  • Returning to bar(1): x = x + 0. Notice that val is never decremented or modified within bar(1)! The argument in the recursive call was val - 1, which does not modify the local variable val. Hence, val remains 1.
  • The loop in bar(1) checks while (val > 0) again: since val=1>0val = 1 > 0 is still true, it calls bar(0) again, receives 0, and repeats indefinitely.

Because the maximum recursion depth never exceeds 3, no stack overflow occurs for bar(3). It runs in an infinite while loop.
Therefore, foo(3) terminates abnormally and bar(3) enters an infinite loop.

Final answer

C

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2017 Computer Science and Information Technology (CS) Session 1
Question
36 of 65, printed as CS Q.36
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.