Consider the following C program: Assume that the input to the program from…
2024
Consider the following C program:

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
Attempted by 208 students.
Show answer & explanation
Correct answer: C
Answer: The program terminates and prints 4321.
Explanation:
Each call to the function reads one character into variable a using getchar().
If the read character is not the newline, the function calls itself recursively to read the next character.
When a newline is read, recursion stops (base case) and the calls begin to return.
After returning from the recursive call, each frame prints its stored character (if it is not the newline). Because printing happens after the recursive call, the last-read character is printed first.
For the input 1234 followed by newline, the characters are printed during unwinding as 4, 3, 2, 1 resulting in output 4321. The newline is not printed.
A video solution is available for this question — log in and enroll to watch it.