Skip to content
Official PYQ · 2015

GATE CS 2015 Set 2 Q15 — Recursion

Explain with AI

Consider the following function written in the C programming langauge :

void foo(char *a)
 {
    if (*a && *a != ' ')
      {
       foo(a+1);
       putchar(*a);
      }
}    

The output of the above function on input "ABCD EFGHABCD \ EFGH" is

Choose one option
View worked solution

Answer: D

The function foo(char *a) is a recursive function that processes the string character by character. Let's analyze the condition in the if statement:

if (*a && *a != ' ')

This condition evaluates to true as long as the current character *a is neither the null terminator ('\0') nor a space character (' ').

When we call foo("$ABCD EFGH$"), the execution proceeds as follows:

  1. foo("$ABCD EFGH$") calls foo("ABCD EFGH$")
  2. foo("ABCD EFGH$")</code> calls <code>foo("BCD EFGH$")
  3. foo("BCD EFGH$")</code> calls <code>foo("CD EFGH$")
  4. foo("CD EFGH$")</code> calls <code>foo("D EFGH$")
  5. foo("D EFGH$")</code> calls <code>foo(" EFGH$")

At foo(" EFGH$"), the current character *a is a space (' '). The condition *a != ' ' becomes false, so this call returns immediately without making any further recursive calls and without printing anything.

Now, the recursion stack unwinds, executing the putchar(*a) statement for each suspended call in reverse order:

  • foo("D EFGH$") resumes and prints 'D'
  • foo("CD EFGH$") resumes and prints 'C'
  • foo("BCD EFGH$") resumes and prints 'B'
  • foo("ABCD EFGH$") resumes and prints 'A'
  • foo("$ABCD EFGH$") resumes and prints '$'

Thus, the final output is DCBADCBA.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Recursion questions