GATE / CS ARCHIVE

SIMILAR QUESTIONS / PROGRAMMING IN C

Trace quotient-and-remainder recursive digit sums

2 questions solved the same way, newest first. Back to Programming in C

How these are solved

Both use the identical unsigned foo(n,r) recurrence n%r + foo(n/r,r), with base n=0 returning0. Only n and radix change: (345,10) versus (513,2).

2 marks · MCQ
Report issue

Recursive sum of decimal digits

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

2 marks · MCQ
Report issue

Recursive sum of binary digits

Recursion

Question 49, 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(513,2) return?

(A) 9
(B) 8
(C) 5
(D) 2
Question 49, 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(513,2) return?

(A) 9
(B) 8
(C) 5
(D) 2
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (23 steps)

The function sums the base-r digits of n. Since 513=512+1=29+1, its binary representation is 1000000001 and has two 1 bits. Consequently foo(513, 2)=2, option D. All intermediate recursive divisions are unsigned integer divisions and terminate at zero.

The successive n values are 513,256,128,64,32,16,8,4,2,1,0. Remainders modulo 2 are 1 at n=513 and n=1 and zero at every other positive step. Summing them produces 2. The exponent 9 tells where the highest bit lies, not how many set bits there are; similarly, the number of recursive positive calls is 10, not the return value. The function counts ones for base 2 because binary digits can only be zero or one.

Original paper, page 14 · Answer key