The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+13 votes

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 new line character.

void reverse(void) 
    int c;
    if(?1) reverse();
    printf("Enter text"); 
  1. $?1$ is $(getchar() != ’\setminus n’)$

    $?2$ is $getchar(c);$
  2. $?1$ is $((c = getchar() ) !=’\setminus n’)$

    $?2$ is $getchar(c);$

  3. $?1$ is $(c != ’\setminus n’)$

    $?2$ is $putchar(c);$

  4. $?1$ is $((c = getchar() ) != ’\setminus n’)$

    $?2$ is $putchar(c);$

asked in Programming by Veteran (59.5k points)
edited by | 1.1k views

3 Answers

+21 votes
Best answer

Here, we are using the '$=$' operator which has less priority than '$!=$' operator. So $(c=getchar())$ has to be in brackets and after reversing the string we use function $putchar(c)$ for printing the character.

So, option (D) is the right answer.

answered by Active (3.3k points)
edited by
how is this reversed??
please elaborate..
explain please
The question has few lines missing. Proper explanation is given here:
But for reversing there need to be a pointer increment statement.Otherwise it will go to infinite loop. So, how will the string reverse without this increment statement?
@Srestha, by backtracking function call stack, printing will be done. No need of incrementing.

@ Swati Rauniyar  

u mean after printing stack will remove that character from the stack, so there will be no need of pointer.

Yes. Function call from A to B to C to D. Space came, return back on stack. Now backtrack. Print D to Print C to Print B to Print A.
+4 votes
getchar() is used to get the input character from the user and putchar() to print the entered character, but before printing reverse is called again and again until ‘\n’ is entered. When ‘\n’ is entered the functions from the function stack run putchar() statements one by one. Therefore, last entered character is printed first.


answered by (357 points)
+2 votes
This problem can be easily solved by elimination.
The output should print the string in reverse order. So option (A) and (B) can be avoided since it do not contain any function call to print. For option (C) and (D), Only (D) has the function to get input. So (D) is the answer.
This reverses the string using recursive approach.
answered by (409 points)

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

37,072 questions
44,646 answers
43,699 users