Question

Consider the following function written in the C programming language.

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

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

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2015 answer key

Solution

Trace the recursive execution of foo with the input string pointer "ABCD EFGH".

The function foo(char *a) checks:
if (*a && *a != ' '):
If true, it recursively calls foo(a+1), and after returning from recursion, calls putchar(*a).

Tracing execution on "ABCD EFGH":

  1. foo("ABCD EFGH"): *a = 'A', calls foo("BCD EFGH")
  2. foo("BCD EFGH"): *a = 'B', calls foo("CD EFGH")
  3. foo("CD EFGH"): *a = 'C', calls foo("D EFGH")
  4. foo("D EFGH"): *a = 'D', calls foo(" EFGH")
  5. foo(" EFGH"): *a = ' ' (space), condition *a != ' ' is false; returns without recursive call or output.

Unwinding the call stack:

  • Level 4 prints *a = 'D'
  • Level 3 prints *a = 'C'
  • Level 2 prints *a = 'B'
  • Level 1 prints *a = 'A'

The characters printed are DCBA.

Final answer

D

Common trap

Assuming foo continues across the space to process the entire string, which would incorrectly yield HGFE DCBA.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 2
Question
25 of 65, printed as CS Q.15
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.