Skip to content
Related Articles

Related Articles

GATE | GATE CS 2011 | Question 49

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 28 Jun, 2021
Improve Article
Save Article

Consider the same 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(513, 2)?
(A) 9
(B) 8
(C) 5
(D) 2


Answer: (D)

Explanation: foo(513, 2) will return 1 + foo(256, 2). All subsequent recursive calls (including foo(256, 2)) will return 0 + foo(n/2, 2) except the last call foo(1, 2) . The last call foo(1, 2) returns 1. So, the value returned by foo(513, 2) is 1 + 0 + 0…. + 0 + 1.
The function foo(n, 2) basically returns sum of bits (or count of set bits) in the number n.

Quiz of this Question

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!