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 "" is
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:
foo("$ABCD EFGH$")callsfoo("ABCD EFGH$")foo("ABCD EFGH$")</code> calls <code>foo("BCD EFGH$")foo("BCD EFGH$")</code> calls <code>foo("CD EFGH$")foo("CD EFGH$")</code> calls <code>foo("D EFGH$")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 .
Free practice · Your answers on this page are not saved.
