Skip to content
Official PYQ · 2011

GATE CS 2011 Q48 — Algorithm Design: Dynamic Programming

Explain with AI

Consider the following recursive C function that takes two arguments.

unsigned int foo(unsigned int n, unsigned int r) {
    if (n>0) return ((n%r) + foo(n/r, r));
    else return 0;
}

What is the return value of the function foo\text{foo} when it is called as foo(345, 10)\text{foo(345, 10)}?

Choose one option
View worked solution

Answer: B

The function foo(n, r) recursively computes the sum of the digits of the number nn when represented in base rr.

Let's trace the execution of foo(345, 10) step-by-step:

  1. foo(345, 10): Since 345>0345 > 0, it returns (345 % 10) + foo(34, 10) which is 5+foo(34,10)5 + \text{foo}(34, 10)
  2. foo(34, 10): Since 34>034 > 0, it returns (34 % 10) + foo(3, 10) which is 4+foo(3,10)4 + \text{foo}(3, 10)
  3. foo(3, 10): Since 3>03 > 0, it returns (3 % 10) + foo(0, 10) which is 3+foo(0,10)3 + \text{foo}(0, 10)
  4. foo(0, 10): Since n=0n = 0, it returns 00.

Substituting the values back, we get:

foo(345,10)=5+4+3+0=12\text{foo}(345, 10) = 5 + 4 + 3 + 0 = 12

Thus, the correct option is B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Algorithm Design: Dynamic Programming questions