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

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();
    ?2 
} 
main() 
{ 
    printf("Enter text"); 
    printf("\n"); 
    reverse(); 
    printf("\n"); 
}
  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.2k 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
0
how is this reversed??
0
please elaborate..
0
explain please
+1
The question has few lines missing. Proper explanation is given here:

http://www.geeksforgeeks.org/c-language-set-5/
0
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?
0
@Srestha, by backtracking function call stack, printing will be done. No need of incrementing.
0

@ Swati Rauniyar  

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

+3
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.
+5 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.

 

Answer(D)
answered by (367 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 (417 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

39,645 questions
46,729 answers
140,391 comments
58,088 users