GATE / CS ARCHIVE

GATE CSE 2017 SET 1 / QUESTION 36

GATE CSE 2017 Set 1 Q36

Programming in C · Recursion · Full GATE CSE 2017 Set 1 paper

GATE 2017 Set 1, Q36 2 marks · MCQ
Report issue

Recursion

Question 36, GATE 2017: 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; }
Classify foo(3),bar(3): A return 6,6; B infinite loop,abnormal termination; C abnormal termination,infinite loop; D both terminate abnormally.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under ordinary finite-stack execution

1. Postdecrement in foo(val--) passes the old value, then decrements the caller’s local copy. Therefore foo(3) calls another foo(3), which calls another foo(3), without reaching a base case.

2. On conventional finite-stack execution, this unbounded recursion exhausts the stack and terminates abnormally. The exam uses that resource model; C does not prescribe a universal stack-overflow mechanism.

3. bar(val−1) passes a smaller value without modifying its caller. Calls descend 3,2,1,0, but bar(1) repeatedly calls bar(0) because its own val remains 1. It loops without return. Intended option C.

Original paper, page 16 · Answer key