Question
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?
Official answer and solution
- Official answer
- C
- From
- Official GATE 2024 answer key
Solution
Trace the local variable a across recursive activation frames of fX() as characters are read and then printed during stack unwinding.
Each recursive call to fX() has its own local variable a on the call stack:
- Call 1 reads
a = '1'('\n') and callsfX(). - Call 2 reads
a = '2'('\n') and callsfX(). - Call 3 reads
a = '3'('\n') and callsfX(). - Call 4 reads
a = '4'('\n') and callsfX(). - Call 5 reads
a = '\n', does not recurse, skipsputchar(a), and returns.
As Calls 4, 3, 2, and 1 unwind in LIFO order, putchar(a) prints '4', '3', '2', '1', producing 4321 before terminating.
Option (C)
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2024 Computer Science and Information Technology - Set 1 (CS1)
- Question
- 19 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.