GATE / CS ARCHIVE

GATE CSE 2005 / QUESTION 31

Recursive digit printing with value parameters

Programming in C · Recursion · Full GATE CSE 2005 paper

GATE 2005, Q31 2 marks · MCQ
Report issue

Recursion

Question 31, GATE 2005: 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);} main sets a=2048, sum=0; calls foo(a, sum); prints sum with newline. Output? A8, 4, 0, 2, 14; B8, 4, 0, 2, 0; C2, 0, 4, 8, 14; D2, 0, 4, 8, 0.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (13 steps)

Calls peel off digits 8, 4, 0, 2, but each prints only after its recursive child returns. Thus the visible digits are 2, 0, 4, 8. The sum parameter is passed by value, so main’s sum stays 0. Assuming the usual stdio declaration, the output is 2, 0, 4, 8, 0 followed by a newline, option D; the commas come from the inner printf format.

Each call stores its own last digit k before recursively processing the remaining prefix. Because printing occurs after the child returns, digits appear from most significant to least:2, 0, 4, 8. The sum variable is a by-value local parameter, so changes do not propagate back into main’s sum. Main consequently appends 0, giving D. This question combines recursive output order with parameter passing, not a digit-sum algorithm that returns its result.

Original paper, page 4