GATE / CS ARCHIVE

GATE CSE 2011 / QUESTION 48

Recursive sum of decimal digits

Programming in C · Recursion · Full GATE CSE 2011 paper

GATE 2011, Q48 2 marks · MCQ
Report issue

Recursion

Question 48, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(345,10) return?

(A) 345
(B) 12
(C) 5
(D) 3
Question 48, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(345,10) return?

(A) 345
(B) 12
(C) 5
(D) 3
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (9 steps)

For positive n and base r>1, n%r is the final base-r digit and integer division n/r removes it. The recursive calls therefore sum the digits. With n=345 and r=10, the return is 5+4+3+0=12, option B.

Unroll the calls: foo(345,10)=5+foo(34,10); foo(34,10)=4+foo(3,10); foo(3,10)=3+foo(0,10); the last call returns 0. The call stack then returns 3,7,12 in reverse order. It does not reconstruct the original number because no place-value multiplications are used, and it does not stop after the first remainder. The base case is essential to terminate after all digits have been consumed.

Original paper, page 14 · Answer key