GATE / CS ARCHIVE

GATE CSE 2008 / QUESTION 61

Recursive string reversal

Programming in C · Recursion · Full GATE CSE 2008 paper

GATE 2008, Q61 2 marks · MCQ
Report issue

Recursion

Question 61, GATE 2008: Fill ?1 and ?2 so this historical C program reverses a newline-terminated input string.
void reverse(void) {
 int c;
 if (?1) reverse();
 ?2
}
main() {
 printf("Enter Text"); printf("\n");
 reverse(); printf("\n");
}

(A) ?1: (getchar()!='\n'); ?2: getchar(c);
(B) ?1: ((c=getchar())!='\n'); ?2: getchar(c);
(C) ?1: (c!='\n'); ?2: putchar(c);
(D) ?1: ((c=getchar())!='\n'); ?2: putchar(c);
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Each invocation must read and retain its own character: ((c=getchar()) != '\n'). Recurse only for a non-newline character, then putchar(c) while unwinding.
2. This prints the input characters in reverse, option D. As written, the base invocation also prints the terminating newline before the reversed characters; main then prints a newline afterward.
3. A and B use getchar instead of output; C tests an uninitialized c. The source uses legacy implicit-int main; interpret the algorithm under its historical C conventions.

Original paper, page 12