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?
Answer
(C)
Explanation
Each call of fX reads one character into its own local variable a. If that character is not a newline, the call recurses first and prints its own character only after the inner call returns, so characters come out in the reverse of the order they were read.
With the input 1234 and a newline, five nested calls read '1', '2', '3', '4' and '\n'. The fifth call neither recurses nor prints, and returns. The waiting calls then print 4, 3, 2 and 1 as they unwind, and main returns.
The newline ends the recursion, so the program terminates (not A) and prints 4321. Printing 1234 would need putchar before the recursive call.
Answer: C