The GATE Grind

GATE 2024 CS (CS1) – Question 19

Programming and Data Structures · Recursion · 1 mark · Multiple choice

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?

  1. The program will not terminate
  2. The program will terminate with no output
  3. The program will terminate with 4321 as output
  4. The program will terminate with 1234 as output

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (C) The program will terminate with 4321 as output

Explanation

Each call reads one character into its own local variable. The calls read `1`, `2`, `3`, `4`, and finally the newline.

The newline call makes no recursive call and prints nothing. As the earlier calls return, each executes `putchar` after its recursive call has finished. They therefore print their saved characters in the order `4`, `3`, `2`, `1`.

The program terminates with output **4321**, option **C**.

More Recursion questions

All Recursion questions →