IAE Academy

GATE 2024 CS1 Q.19: solution and answer

GATE 2024 · CS1Q.19 · 1 mark · MCQ

Consider the following C program:

#include <stdio.h>
void fX();
int main(){
    fX();
    return 0;}
void fX(){
  char a;
  if((a=getchar()) != '\n')
      fX();
  if(a != '\n')
      putchar(a);}

Assume that the input to the program from the command line is 1234 followed by a newline character. Which one of the following statements is CORRECT?

GATE 2024 CS1 question 19: The question shows two side-by-side C code panels separated by a vertical divider line (a typical two-column print layout…Tap to open full size
Figure from the GATE 2024 CS1 paper. It is part of the question.
Figure description

The question shows two side-by-side C code panels separated by a vertical divider line (a typical two-column print layout for a short program, not a diagram). Left panel: #include <stdio.h>; void fX(); int main() fX(); return 0;. Right panel: void fX() char a; if((a=getchar()) != ' ') fX(); if(a != ' ') putchar(a);. Below both panels, on the full page width, is the input assumption sentence, then the four MCQ options.

  1. (A)

    The program will not terminate

  2. (B)

    The program will terminate with no output

  3. (C)

    The program will terminate with 4321 as output

  4. (D)

    The program will terminate with 1234 as output

Answer and solution

ANSWER

The program terminates and prints 4321, option (C).

Official answer: CSource: Official answer key, GATE 2024 CS1 (IISc Bengaluru)

  1. Each call of fX reads one character into its own local variable a, so every call keeps its own character: the first four calls hold '1', '2', '3' and '4'.

  2. Input 1234 followed by a newline: the first call reads '1' and, since it is not '\n', calls fX again; the next calls read '2', '3' and '4' in turn and each calls fX again.

  3. The fifth call reads '\n', so it does not recurse. Its test a != '\n' is false, so it prints nothing and returns.

  4. Control now returns through the earlier calls in reverse order. Each one reaches putchar(a) after its recursive call has finished, so the call holding '4' prints first, then '3', then '2', then '1'.

  5. The recursion stops at the newline, so the program terminates, and the output is 4321. The answer is (C).

KEY IDEA

Each call keeps its own local character and prints it only after the deeper call returns, so characters read left to right are printed right to left: the recursion reverses the input.

WATCH OUT FOR

Expecting the characters in the order they were read (1234, option D), or thinking the newline stops all output (option B). The newline only stops the recursion and is itself never printed; every earlier call still prints its own character on the way back.

From the GATE 2024 CS1 paper. Every question of this paper · Download the full paper · All 9 Recursion questions, with notes

More Recursion questions