Choose the correct option to fill and 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");
}View worked solution
Answer: D
To print an input string in reverse order using recursion, we need to read characters one by one, store them, recursively call the function to process the rest of the string, and then print the stored characters as the recursion unwinds.
Step-by-Step Analysis:
- Local Variable Storage:
Inside the
reverse()function,int c;is declared as a local variable. Each recursive call toreverse()gets its own instance ofcallocated on the stack. - Condition ():
We must read a character, store it in the local variable
c, and check if it is the newline character ('\n') which terminates the input.
This is correctly achieved by:((c = getchar()) != '\n')
If the character is not'\n', the function calls itself recursively to process the next character. - Printing ():
Once the base case is reached (i.e.,
'\n'is encountered), the recursion starts unwinding. As each suspended function call resumes, it must print its stored characterc.
This is done using:putchar(c);
Since the last-read character is printed first during the unwinding of the call stack, the string is printed in reverse order.
Option Elimination:
- Options A & B: The statement
getchar(c);is syntactically invalid in C becausegetchar()does not take any arguments. - Option C: The variable
cis used in the condition(c != '\n')before any value is read into it, resulting in undefined behavior. - Option D: Correctly reads and stores the character in
c, checks the termination condition, and prints it usingputchar(c).
Free practice · Your answers on this page are not saved.
