Common data questions
Common Data for Questions 48 and 49:
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;
}
Shared with question 48.
Question
What is the return value of the function foo when it is called as foo(513, 2)?
Official answer and solution
- Official answer
- D
- From
- Official GATE 2011 answer key
Solution
Trace the recursive function execution for base 2.
- Calling
foo(n, 2)computes the sum of the binary bits (the Hamming weight or number of set bits) of .
- Represent in binary:
- The binary representation of 513 contains exactly two 1s and eight 0s.
- Summing all binary digits yields .
Final answer
D
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2011 Computer Science and Information Technology (CS)
- Question
- 49 of 65, printed as CS Q.49
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.