Consider the following recursive C function that takes two arguments. unsigned…
2011
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 when it is called as foo(345, 10)?
- A.
345
- B.
12
- C.
5
- D.
3
Attempted by 239 students.
Show answer & explanation
Correct answer: B
Key idea: the function returns the sum of the digits of n when written in base r by adding n%r and recursing on n/r.
Step-by-step evaluation of foo(345, 10):
First call: n = 345. Compute n % 10 = 5 and recurse with n / 10 = 34. Contribution = 5.
Second call: n = 34. Compute n % 10 = 4 and recurse with n / 10 = 3. Contribution = 4.
Third call: n = 3. Compute n % 10 = 3 and recurse with n / 10 = 0. Contribution = 3.
Base case: n = 0 returns 0, so recursion stops.
Sum the contributions: 5 + 4 + 3 = 12. Therefore, foo(345, 10) returns 12.
General note: the function computes the sum of digits of n in base r by repeatedly taking the remainder and dividing by r.
A video solution is available for this question — log in and enroll to watch it.