Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the following C program:

#include \(\lt\)stdio.h\(\gt\)
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

Answer: C

The program terminates with 4321 as output.

Each call to fX reads one character into its own local variable a. If it is not a newline, it calls fX again before printing. So the calls nest: the first reads '1', the second '2', the third '3', the fourth '4', and the fifth reads the newline and does not recurse.

Now the calls return in reverse order. The fifth call holds the newline and prints nothing. The fourth prints '4', the third '3', the second '2' and the first '1'. Output: 4321. The recursion depth is bounded by the input length, so the program terminates, and it does produce output; printing happens after the recursive call, which is why the order is reversed rather than 1234.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.