Consider the following C-program:
void foo (int n, int sum) {
int k = 0, j = 0;
if (n == 0) return;
k = n % 10; j = n/10;
sum = sum + k;
foo (j, sum);
printf ("%d,",k);
}
int main() {
int a = 2048, sum = 0;
foo(a, sum);
printf("%d\n", sum);
}
What does the above program print?
View worked solution
Answer: D
To find the output of the program, we trace the execution step-by-step:
- Pass-by-Value Behavior: In C, arguments are passed by value. The variable
suminmain()is passed tofoo(). Any modifications tosuminsidefoo()are local to the activation records offoo()and do not affect the variablesuminmain(). Thus, the finalprintf("%d\n", sum)inmain()will print0. - Tracing the Recursion:
foo(2048, 0): , , local . Callsfoo(204, 8). Prints after returning.foo(204, 8): , , local . Callsfoo(20, 12). Prints after returning.foo(20, 12): , , local . Callsfoo(2, 12). Prints after returning.foo(2, 12): , , local . Callsfoo(0, 14). Prints after returning.foo(0, 14): Base case reached (), returns immediately.
As the recursion unwinds, the printf statements execute in reverse order of the calls (Last-In, First-Out):
foo(2, 12)prints2,foo(20, 12)prints0,foo(204, 8)prints4,foo(2048, 0)prints8,
Finally, main() prints the original value of sum, which is 0. Thus, the complete output is 2,0,4,8,0.
Free practice · Your answers on this page are not saved.
