1.6k 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);$

edited | 1.6k views

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.

edited
0
how is this reversed??
0
0
+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

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

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.
+1 vote

$getchar()$ - reads a single character at a time from the $stdin$.

$putchar(c)$ - writes a character specified by the argument to $stdout$.

As getchar() and putchar() both are needed to read the string and print its reverse and only option D contains both the function. D is the answer.

Now coming to the code.

$reverse(void)$ is calling itself recursively. when \n is encountered $putchar()$ gets executed and prints the last character and then the function returns to its previous call and prints last 2nd character and so on.