GATE CS 2024 Set 1 — Question 19

MCQ+1 / -0.33MediumFunctions & RecursionC ProgrammingProgramming & Data Structures

Programming & Data Structures → C Programming → Functions & Recursion

Last updated

Question

Consider the following C program:
#include 
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

Correct answer

(C) The program will terminate with 4321 as output

Solution

The function fX() is a recursive function that reads characters from the standard input one by one.
1.Base Case: The recursion stops when getchar() reads a newline character '\n'. At this point, the if((a=getchar()) != '\n') condition fails, and the function starts returning.
2.Recursive Step: For any character other than '\n', the function calls itself recursively: fX(). This pushes the current character a onto the function call stack.
3.Post-recursion Action: After the recursive call returns, the function executes if(a != '\n') putchar(a);. This prints the character that was read before the recursive call.
Because the printing happens after the recursive call returns, the characters are printed in the reverse order of their arrival (Last-In, First-Out behavior).
Execution Trace for input "1234\n":
  • fX() (1st call) reads '1', calls fX() (2nd call).
  • fX() (2nd call) reads '2', calls fX() (3rd call).
  • fX() (3rd call) reads '3', calls fX() (4th call).
  • fX() (4th call) reads '4', calls fX() (5th call).
  • fX() (5th call) reads '\n', the condition ('\n' != '\n') is false. It skips the recursive call and the putchar (since a == '\n'), then returns to the 4th call.
  • fX() (4th call) resumes, a is '4', putchar('4') prints 4, returns to 3rd call.
  • fX() (3rd call) resumes, a is '3', putchar('3') prints 3, returns to 2nd call.
  • fX() (2nd call) resumes, a is '2', putchar('2') prints 2, returns to 1st call.
  • fX() (1st call) resumes, a is '1', putchar('1') prints 1, returns to main().
The final output is 4321. Therefore, option (C) is correct.

More questions on C Programming

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free