GATE / CS ARCHIVE

GATE CSE 2015 SET 2 / QUESTION 21

GATE CSE 2015 Set 2 Q21

Programming in C · Recursion · Full GATE CSE 2015 Set 2 paper

GATE 2015 Set 2, Q21 1 mark · MCQ
Report issue

Recursion

Question 21, GATE 2015: C function foo(char*a){if(*a && *a!=' '){foo(a+1); putchar(*a); }}. Output for string “ABCD EFGH”? A ABCD EFGH; B ABCD; C HGFE DCBA; D DCBA.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Recursion stops at the first space without advancing beyond it. Each earlier character is printed only after its recursive call returns, reversing ABCD and producing DCBA, D.

The condition stops recursion when the pointer reaches either the terminator or the first space. Starting at A, the function calls on B, C, D and then the space, where it returns without printing. Printing occurs after each recursive call, so unwinding emits D, C, B, A. No invocation reaches EFGH. Had putchar preceded the recursive call, the first word would print forward instead.

Original paper, page 33 · Answer key