Skip to content
Official PYQ · 2008

GATE CS 2008 Q61 — Programming in C

Explain with AI

Choose the correct option to fill ?1?1 and ?2?2 so that the program below prints an input string in reverse order. Assume that the input string is terminated by a new line character.

void reverse(void) 
{ 
    int c;
    if(?1) reverse();
    ?2 
} 
main() 
{ 
    printf("Enter text"); 
    printf("\n"); 
    reverse(); 
    printf("\n"); 
}
Choose one option
View worked solution

Answer: D

To print an input string in reverse order using recursion, we need to read characters one by one, store them, recursively call the function to process the rest of the string, and then print the stored characters as the recursion unwinds.

Step-by-Step Analysis:

  1. Local Variable Storage: Inside the reverse() function, int c; is declared as a local variable. Each recursive call to reverse() gets its own instance of c allocated on the stack.
  2. Condition (?1?1): We must read a character, store it in the local variable c, and check if it is the newline character ('\n') which terminates the input.
    This is correctly achieved by: ((c = getchar()) != '\n')
    If the character is not '\n', the function calls itself recursively to process the next character.
  3. Printing (?2?2): Once the base case is reached (i.e., '\n' is encountered), the recursion starts unwinding. As each suspended function call resumes, it must print its stored character c.
    This is done using: putchar(c);
    Since the last-read character is printed first during the unwinding of the call stack, the string is printed in reverse order.

Option Elimination:

  • Options A & B: The statement getchar(c); is syntactically invalid in C because getchar() does not take any arguments.
  • Option C: The variable c is used in the condition (c != '\n') before any value is read into it, resulting in undefined behavior.
  • Option D: Correctly reads and stores the character in c, checks the termination condition, and prints it using putchar(c).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions