Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q36 — Recursion

Explain with AI

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)foo(3) and bar(3)bar(3) will result in:

Choose one option
View worked solution

Answer: C

Let us analyze the execution of both functions starting with the input 3:

1. Execution of foo(3):

  • Inside foo(3), the loop condition val > 0 (3 > 0) is true.
  • The statement x = x + foo(val--) is executed.
  • The post-decrement operator val-- passes the current value of val (which is 3) to the recursive call first, and then decrements val to 2.
  • This results in a recursive call to foo(3).
  • This process repeats indefinitely, causing infinite recursion. Since each recursive call consumes stack space, it quickly leads to a stack overflow, resulting in abnormal termination.

2. Execution of bar(3):

  • Inside bar(3), val = 3. It calls bar(2), which calls bar(1), which in turn calls bar(0).
  • bar(0) returns 0 immediately because the loop condition val > 0 is false.
  • Control returns to bar(1). The statement x = x + bar(0) completes, and x becomes 0.
  • The loop condition val > 0 is checked again in bar(1). Since val is still 1 (it was never decremented or modified inside bar), the condition remains true.
  • This causes bar(1) to call bar(0) repeatedly in an infinite loop without growing the stack indefinitely.

Thus, foo(3) terminates abnormally, and bar(3) enters an infinite loop.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Recursion questions