GATE / CS ARCHIVE

GATE CSE 2019 / QUESTION 26

An unreachable recursive base case

Programming in C · Recursion · Full GATE CSE 2019 paper

GATE 2019, Q26 2 marks · MCQ
Report issue

Recursion

Question 26, GATE 2019: For positive integer n, convert(n) executes: if(n<0) printf("%d",n); else { convert(n/2); printf("%d",n%2); }. Decide whether it prints ordinary binary and terminates (A), reversed binary and terminates (B), binary without terminating (C), or nothing without terminating (D).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

1. The stopping branch is n<0, not n==0. Integer division of a positive integer by 2 produces another nonnegative integer, so none of the recursive calls can enter the stopping branch.
2. Repeated halving eventually reaches zero. For example, an input 5 gives calls with arguments 5, 2, 1, 0. At zero the else branch calls convert(0/2), which is convert(0) again.
3. Each printf in the else branch occurs after the recursive call. Since the innermost call never returns normally, no pending printf is reached. The negative-argument printf is also unreachable.
4. Therefore the abstract recursion neither prints nor terminates: D. A real implementation has finite resources and typically exhausts its call stack, rather than literally running forever. The familiar binary-conversion algorithm would need a reachable base case; it cannot be substituted for the code actually supplied.

Original paper, page 9 · Answer key