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:
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 () 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: callsbar(2). Inbar(2),val = 2 > 0: callsbar(1). Inbar(1),val = 1 > 0: callsbar(0).- In
bar(0),val > 0is false ( is false), sobar(0)immediately returns 0 without further recursion. - Returning to
bar(1):x = x + 0. Notice thatvalis never decremented or modified withinbar(1)! The argument in the recursive call wasval - 1, which does not modify the local variableval. Hence,valremains 1. - The loop in
bar(1)checkswhile (val > 0)again: since is still true, it callsbar(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.
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.