GATE / CS ARCHIVE

GATE CSE 2024 SET 1 / QUESTION 19

Print on recursive return to reverse input

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

GATE 2024 Set 1, Q19 1 mark · MCQ
Report issue

Recursion

Question 19, GATE 2024: main calls fX once. The function has local char a; it reads a=getchar(), recursively calls fX if a is not newline, then prints a with putchar if a is not newline. Input is 1234 followed by newline. A no termination; B termination with no output; C termination with 4321; D termination with 1234.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Approach: Distinguish the order in which recursive calls read characters from the order in which suspended calls resume printing.
1. The first call stores '1' in its own local a and calls fX again before reaching putchar. The next calls similarly store '2', '3' and '4'. Each call has a separate local variable.
2. A fifth call reads the newline. Both conditions are false, so this call neither recurses nor prints and returns immediately.
3. The suspended call holding '4' now continues at its second condition and prints 4. Returning again prints 3, then 2, then 1.
4. Once the first call returns, main terminates. The newline itself is never printed.
Answer: C, output 4321. Printing before the recursive call would preserve input order; printing after it reverses order. The explicitly supplied newline is the stopping condition, so no assumption about reading past end-of-file is needed.
The printed program uses typographic single quotation marks. Taken literally these are not valid C delimiters, so the program does not compile as printed. The answer above follows the intended textbook interpretation with ASCII quote delimiters.

Original paper, page 13 · Answer key