Question

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?

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2024 answer key

Solution

Trace the local variable a across recursive activation frames of fX() as characters are read and then printed during stack unwinding.

Each recursive call to fX() has its own local variable a on the call stack:

  1. Call 1 reads a = '1' (≠\neq '\n') and calls fX().
  2. Call 2 reads a = '2' (≠\neq '\n') and calls fX().
  3. Call 3 reads a = '3' (≠\neq '\n') and calls fX().
  4. Call 4 reads a = '4' (≠\neq '\n') and calls fX().
  5. Call 5 reads a = '\n', does not recurse, skips putchar(a), and returns.

As Calls 4, 3, 2, and 1 unwind in LIFO order, putchar(a) prints '4', '3', '2', '1', producing 4321 before terminating.

Final answer

Option (C)

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 1 (CS1)
Question
19 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.