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 when it is called as ?
View worked solution
Answer: B
The function foo(n, r) recursively computes the sum of the digits of the number when represented in base .
Let's trace the execution of foo(345, 10) step-by-step:
foo(345, 10): Since , it returns(345 % 10) + foo(34, 10)which isfoo(34, 10): Since , it returns(34 % 10) + foo(3, 10)which isfoo(3, 10): Since , it returns(3 % 10) + foo(0, 10)which isfoo(0, 10): Since , it returns .
Substituting the values back, we get:
Thus, the correct option is B.
Free practice · Your answers on this page are not saved.
