The GATE Grind

GATE 2011 CS (CS1) – Question 58

Programming and Data Structures · Recursion · 2 marks · Multiple choice

Find foo(345,10).

unsigned int foo(unsigned int n, unsigned int r) {
    if (n>0) return (n%r)+foo(n/r,r);
    else return 0;
}
  1. 345
  2. 12
  3. 5
  4. 3

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (B) 12

Explanation

Each call adds the current least-significant base-r digit n%r and recurses on the remaining digits n/r. In base ten the digits of 345 sum to 5+4+3=12. Thus B.

More Recursion questions

All Recursion questions →