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: D
The given recursive function foo(n, r) computes the sum of the digits of the number when represented in base .
Analysis of the Function
n % rextracts the least significant digit of in base .n / rperforms an integer division, effectively shifting to the right by one digit in base .- The recursion terminates when , returning .
Therefore, foo(n, r) returns the sum of the digits of in base .
Calculation for foo(513, 2)
Here, and (binary representation).
We express in binary (base 2):
The sum of the binary digits (the number of set bits) is:
Thus, the function returns 2.
Free practice · Your answers on this page are not saved.
