Consider the C functions foo and bar given below: int foo(int val) { int x=0;…
2017
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:
- A.
Return of 6 and 6 respectively.
- B.
Infinite loop and abnormal termination respectively.
- C.
Abnormal termination and infinite loop respectively.
- D.
Both terminating abnormally.
Attempted by 78 students.
Show answer & explanation
Correct answer: C
Answer: Abnormal termination and infinite loop respectively.
Why the first function (foo) terminates abnormally:
In foo, the call foo(val--) passes the current value of val to the recursive call and then decrements val. Because the recursive call receives the same argument as the caller, the recursion never progresses toward a base case. Each call creates a new stack frame and recursion grows until the stack overflows, causing abnormal termination.
Why the second function (bar) results in an infinite loop:
In bar, the call bar(val-1) invokes the function with a smaller value, so those inner calls can return. However, the loop variable val in the current frame is never modified inside the while loop. The condition while(val > 0) therefore remains true forever, and the function repeatedly calls smaller instances that return, but the caller never updates its own val to stop the loop. This produces a non-terminating loop (infinite loop), not stack overflow.
Trace for foo(3): foo(3) calls foo(3) again (post-decrement passes 3), which calls foo(3) again, and so on until the stack overflows.
Trace for bar(3): bar(3) calls bar(2) → bar(1) → bar(0) which returns. But bar(1) still has val == 1, so its while loop repeats calling bar(0) forever, causing an infinite loop.
Key takeaway: distinguish between changing the argument passed to a recursive call and changing the loop variable in the current frame. Post-decrement passes the old value (leading to unbounded recursion here), while calling with val-1 without updating val leaves the loop condition unchanged.
A video solution is available for this question — log in and enroll to watch it.