Choose the correct option to fill ?1 and ?2 so that the program below prints…

2008

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

void reverse(void)
 {
  int c;
  if (?1) reverse();
  ?2
}
int main()
{
  printf ("Enter Text ") ;
  printf ("\\n") ;
  reverse();
  printf ("\\n") ;
}

  1. A.
    ?1 is (getchar() != ’\\n’)
    ?2 is getchar(c);
  2. B.
    ?1 is (c = getchar() ) != ’\\n’)
    ?2 is getchar(c);

  3. C.
    ?1 is (c != ’\\n’)
    ?2 is putchar(c);

  4. D.
    ?1 is ((c = getchar()) != ’\\n’)
    ?2 is putchar(c);

Attempted by 102 students.

Show answer & explanation

Correct answer: D

Correct implementation: Replace ?1 with ((c = getchar()) != '\n') and ?2 with putchar(c). The complete function is:

void reverse(void) { int c; if ((c = getchar()) != '\n') reverse(); putchar(c); }

  • Assign and test: (c = getchar()) reads the next character and returns it for comparison with '\n'. This both reads input and detects the end-of-line.

  • Recursion: If the read character is not the newline terminator, call reverse() to process the rest of the input first.

  • Output after recursion: putchar(c) prints the character after the deeper calls have printed later characters, so characters appear in reverse order.

Example: input 'a','b','c','\n' causes recursive reads for a, b, c; when the newline is seen recursion stops, then putchar prints 'c', 'b', 'a', producing the reversed string.

Explore the full course: Gate Guidance By Sanchit Sir