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?

A.

The program will not terminate

B.

The program will terminate with no output

C.

The program will terminate with 4321 as output

D.

The program will terminate with 1234 as output

Solution:

Here's how the program works:

  • The 'main' function simply calls the function 'fX';.
  • When 'fX' is called, it reads a character using 'getchar()' and assigns it to variable 'a'.
  • If 'a' is not equal to '\n' (a newline character), the function 'fX' is called recursively again.
  • Once the newline character is encountered, the condition is false and will continue the execution.
  • During unwinding, the function checks if 'a' is not equal to '\n' again it prints the character using 'putchar(a)'.

This will continue until all characters are printed in reverse order.

So according to the program, the correct option is C.