Consider the following function written in the C programming language. void…
2015
Consider the following function written in the C programming language.
void foo(char *a) { if (*a && *a != ' ') { foo(a+1); putchar(*a); } }he output of the above function on input “ABCD EFGH” is
- A.
ABCD EFGH
- B.
ABCD
- C.
HGFE DCBA
- D.
DCBA
Attempted by 219 students.
Show answer & explanation
Correct answer: D
Explanation: how the function works and why the output is "DCBA".
Base case: If the current character is the null terminator or a space, the function returns without printing.
Recursive step: If the current character is nonzero and not a space, the function calls itself with the next character (a+1) and then calls putchar on the current character after returning from recursion.
Effect: Characters before the stopping point (space or end) are printed in reverse order because printing happens after the recursive call.
Trace for input "ABCD EFGH":
The call starts at 'A', which calls for 'B', which calls for 'C', which calls for 'D', which calls for the space.
At the space, the condition (*a && *a != ' ') fails, so recursion stops and nothing is printed for the space or any characters after it.
As recursion unwinds, putchar prints 'D', then 'C', then 'B', then 'A'.
Final output: DCBA