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 and will result in:
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 conditionval > 0(3 > 0) is true. - The statement
x = x + foo(val--)is executed. - The post-decrement operator
val--passes the current value ofval(which is3) to the recursive call first, and then decrementsvalto2. - 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 callsbar(2), which callsbar(1), which in turn callsbar(0). bar(0)returns0immediately because the loop conditionval > 0is false.- Control returns to
bar(1). The statementx = x + bar(0)completes, andxbecomes0. - The loop condition
val > 0is checked again inbar(1). Sincevalis still1(it was never decremented or modified insidebar), the condition remains true. - This causes
bar(1)to callbar(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.
