Consider the following program:
#include <stdio.h>
void fX ();
int main(){
fX();
return 0 };
void fX () {
char a;
if ((a=g e t c h a r()) ! = '\n')
fX();
if (a ! = '\n')
putchar (a); }
Assume that the input to the program from the command line is followed by a newline character. Which one of the following statements is CORRECT?
View worked solution
Answer: C
The function fX() reads characters from the input one by one using recursion until it encounters a newline character ('\n').
Let's trace the execution with the input 1234\n:
- First call: Reads
'1'. Since'1' != '\n', it callsfX()recursively. - Second call: Reads
'2'. Since'2' != '\n', it callsfX()recursively. - Third call: Reads
'3'. Since'3' != '\n', it callsfX()recursively. - Fourth call: Reads
'4'. Since'4' != '\n', it callsfX()recursively. - Fifth call: Reads
'\n'. Since'\n' != '\n'is false, the recursion stops. The conditiona != '\n'is false, so it returns without printing.
As the recursion unwinds, the pending putchar(a) statements are executed in reverse order of the calls:
- Fourth call resumes and prints
'4'. - Third call resumes and prints
'3'. - Second call resumes and prints
'2'. - First call resumes and prints
'1'.
Thus, the program terminates and outputs 4321.
Free practice · Your answers on this page are not saved.
