Recursive I/O with getchar and printing on unwinding: if the user inputs the characters a, b, c followed by Enter, what will this program print?
#include
int main()
{
void fun();
fun();
printf("
");
return 0;
}
void fun()
{
char c;
if ((c = getchar()) != '
')
fun();
printf("%c", c);
}
Select the exact output sequence.
-
Aabc abc
-
Bbca
-
CInfinite loop
-
Dcba
-
ENone of the above
Answer
Correct Answer: cba
Explanation
Introduction / Context:This tests understanding of recursion order and when output happens relative to input. The function fun reads one character at a time until a newline, then prints characters after the recursive calls return, producing reverse order.
Given Data / Assumptions:
- User types: a, then b, then c, then Enter (newline).
- The recursion continues while the read character is not newline.
- Printing occurs after the recursive call returns, during the unwinding phase.
- printf in main adds a trailing newline at the end.
Concept / Approach:With post-recursive printing, the deepest call corresponds to the last non-newline character read. As the stack unwinds, characters are printed in last-in-first-out order, i.e., reversed.
Step-by-Step Solution:User enters 'a': c = 'a' (not newline) → recurse.Then 'b': c = 'b' → recurse.Then 'c': c = 'c' → recurse.Then newline: c = '' → no further recursion; print '' as the base case prints the newline character (it prints at the end, but here the code prints c even when it is newline, yielding a line break).Unwinding: prints 'c', then 'b', then 'a' in that order; main prints another newline.
Verification / Alternative check:Run the code and type abc followed by Enter. You will see cba printed (with a newline because both the base case prints newline and main prints a newline).
Why Other Options Are Wrong:'abc abc' / 'bca': These assume forward-order or mixed-order printing.Infinite loop: Termination occurs upon reading newline.
Common Pitfalls:Expecting pre-recursive printing; overlooking that printf("%c", c) is executed after recursive call returns; forgetting that the newline character will also be printed by this code.
Final Answer:cba