Skip to content
Official PYQ · 2024

GATE CS 2024 Set 1 Q9 — Programming in C

Explain with AI

 

​​​Consider the following C\mathrm{C} 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 12341234 followed by a newline character. Which one of the following statements is CORRECT?

Choose one option
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:

  1. First call: Reads '1'. Since '1' != '\n', it calls fX() recursively.
  2. Second call: Reads '2'. Since '2' != '\n', it calls fX() recursively.
  3. Third call: Reads '3'. Since '3' != '\n', it calls fX() recursively.
  4. Fourth call: Reads '4'. Since '4' != '\n', it calls fX() recursively.
  5. Fifth call: Reads '\n'. Since '\n' != '\n' is false, the recursion stops. The condition a != '\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.

Published
Report a correction
Keep exploringMore Programming in C questions