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: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?
#include
void fX();
int main(){
fX();
return 0;} void fX(){
char a;
if((a=getchar()) != '\n')
fX();
if(a != '\n')
putchar(a);}
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
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":if(a != '\n') putchar(a);. This prints the character that was read before the recursive call.fX()(1st call) reads '1', callsfX()(2nd call).fX()(2nd call) reads '2', callsfX()(3rd call).fX()(3rd call) reads '3', callsfX()(4th call).fX()(4th call) reads '4', callsfX()(5th call).fX()(5th call) reads '\n', the condition('\n' != '\n')is false. It skips the recursive call and theputchar(sincea == '\n'), then returns to the 4th call.fX()(4th call) resumes,ais '4',putchar('4')prints 4, returns to 3rd call.fX()(3rd call) resumes,ais '3',putchar('3')prints 3, returns to 2nd call.fX()(2nd call) resumes,ais '2',putchar('2')prints 2, returns to 1st call.fX()(1st call) resumes,ais '1',putchar('1')prints 1, returns tomain().
More questions on C Programming
2024 Set 2 Q13Consider the following C program. Assume parameters to a function are evaluated from right to left.…2024 Set 2 Q17Let be the adjacency matrix of a simple undirected graph . Suppose is its own inverse.…2024 Set 1 Q17Given an integer array of size , we want to check if the array is sorted (in either ascending or…2024 Set 1 Q18Consider the following C program: [code] Which one of the following statements is CORRECT?2024 Set 1 Q21In a tree, the requirement of at least half-full (50%) node occupancy is relaxed for which…
Practice GATE CS PYQs with adaptive difficulty
Timed practice, skill tracking, and AI explanations — free to start.
Start practicing free