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

2004

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

#include <stdio.h>
void wrt_it (void);
int main (void)
{
    printf("Enter Text"); 
    printf ("\n");
    wrt_ it();
    printf ("\n");
    return 0;
}
void wrt_it (void)
{
    int c;
    if (?1)
        wrt_it();
    ?2
}

  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 47 students.

Show answer & explanation

Correct answer: D

Correct replacements: ?1 should be (c = getchar()) != '\n' and ?2 should be putchar(c).

Explanation: The function reads a character into c and, if it is not the newline character, calls itself recursively to process the remaining input. After the recursive call returns, putchar(c) outputs the character just read. This causes the characters to be printed in reverse order.

  1. Step 1: Read a character and test for newline using assignment inside the condition: (c = getchar()) != '\n'. This both fetches the character and lets you inspect it.

  2. Step 2: If the character is not a newline, recurse to process the rest of the input. The recursive calls descend until a newline is seen.

  3. Step 3: After recursion returns, call putchar(c) to print the stored character. Because printing happens after deeper recursive calls, characters are output in reverse.

Common mistakes and why they are wrong:

  • Calling getchar() in the condition without assigning it to c discards the character for later output.

  • Using getchar(c) is invalid because getchar takes no argument. To print a stored character use putchar(c).

  • Checking c != '\n' without assigning c first tests an uninitialized value; the assignment (c = getchar()) must occur before or as part of the test.

Implementation note: Declare c as int (not char) because getchar() returns int to allow EOF detection.

Explore the full course: Gate Guidance By Sanchit Sir