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
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":
foo("ABCD EFGH"):*a = 'A', callsfoo("BCD EFGH")foo("BCD EFGH"):*a = 'B', callsfoo("CD EFGH")foo("CD EFGH"):*a = 'C', callsfoo("D EFGH")foo("D EFGH"):*a = 'D', callsfoo(" EFGH")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.
D
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.