Consider the following C-program: void foo(int n, int sum) { int k = 0, j = 0;…
2005
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);
getchar();
}
What does the above program print?
- A.
8, 4, 0, 2, 14
- B.
8, 4, 0, 2, 0
- C.
2, 0, 4, 8, 14
- D.
2, 0, 4, 8, 0
Attempted by 159 students.
Show answer & explanation
Correct answer: D
Answer: The program prints 2, 0, 4, 8, 0
Explanation:
Each call of foo extracts the last digit k = n % 10 and then calls foo on the remaining digits. The printf that prints k runs after the recursive call returns, so printing happens during the recursion unwind.
Because printing occurs after the recursive call, the digits are printed from the most significant to the least significant digit of the original number. For 2048 that yields 2, 0, 4, 8.
The parameter sum is passed by value. Updates to sum inside foo affect only the local copy in that call and do not change the sum variable in main, so the final printf in main prints 0.
Step-by-step (key frames):
Call foo(2048, 0): k = 8, local sum = 8 -> calls foo(204, 8)
Call foo(204, 8): k = 4, local sum = 12 -> calls foo(20, 12)
Call foo(20, 12): k = 0, local sum = 12 -> calls foo(2, 12)
Call foo(2, 12): k = 2, local sum = 14 -> calls foo(0, 14) which returns immediately
Unwinding prints k from each frame: 2, 0, 4, 8
Finally main prints its own sum (unchanged): 0