What does the following recursive function do Give a highlev
What does the following recursive function do? Give a high-level description, don\'t just reword the code into English (e.g., \"if the number is one then it returns 0\").
// assume number is always greater than 1
public static int foo(int number) {
if(number == 1)
return 0;
else
return 1 + foo(number/2);
}
Solution
Answer:
When we call this method, this method will recursively call itself until passed value reaches 1.
Lets take an example.
we passed 10 value to the function so whle calling this function \"number\" variable value is 10.
if condtion will return false because number == 1 is false here so else part will execute.
here we are adding 1 to the result and calling this function again with half of the the number that we passed.
so now we are calling this function foo(10/2) = foo(5).
So number variable value is 5 again if condition will return false so else part will execute.
Again 1 will add to the result. In previous iteration 1 value already added to the result so now value become 2.
Again we foo() method will called now foo(5/2) = foo(2). Now number variable value is 2
Again if condition will fail and else part will execute.
1 value will be added to the result. So 2 + 1 =3.
again foo() method will be called. This time foo(2/2) = foo(1)
Now number variable value is 1. If condition will return true so if block will execute and 0 value will be added to the result. 3 + 0 = 3.
Finally this method will return value 3 if we pass number vairable value as 10 to this function.
