The GATE Grind

GATE 2015 CS (CS2) – Question 21

Programming and Data Structures · Recursion · 1 mark · Multiple choice

What does foo("ABCD EFGH") print?

void foo(char *a) {
  if (*a && *a != ' ') {
    foo(a+1);
    putchar(*a);
  }
}
  1. ABCD EFGH
  2. ABCD
  3. HGFE DCBA
  4. DCBA

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) DCBA

Explanation

Recursion advances until the first space, where the condition fails. Printing occurs during unwinding, so the preceding characters D,C,B,A are printed in reverse order. Characters after the space are never visited. Thus D.

More Recursion questions

All Recursion questions →