143k views
2 votes
Consider the following method:

public static int puzzle(int num)

{

if (num <= 1)

return 1;

else

return num + puzzle(num / 2);

}

What will be returned after the following method call?

puzzle(5)

10

12

8

14

1 Answer

4 votes

Answer:

The method `puzzle` is a recursive method that takes an integer `num` as input and returns an integer. It adds the value of the input `num` to the result of calling the `puzzle` method recursively with `num/2` as the argument.

To determine the value that will be returned after the following method call `puzzle(5)`, we can work through the steps of the method as follows:

1. The initial value of `num` is 5.

2. Since 5 is greater than 1, the else block is executed.

3. The value of `num` (which is 5) is added to the result of calling `puzzle` recursively with `num/2` (which is 2) as the argument.

4. The value of `num` in the recursive call is now 2.

5. Since 2 is greater than 1, the else block is executed.

6. The value of `num` (which is 2) is added to the result of calling `puzzle` recursively with `num/2` (which is 1) as the argument.

7. The value of `num` in the recursive call is now 1.

8. Since 1 is less than or equal to 1, the if block is executed and the value 1 is returned.

9. The value of the recursive call with `num/2` equal to 1 (which is 1) is added to the current value of `num` (which is 2).

10. The final result is 2+1 = 3.

Therefore, the value that will be returned after the following method call `puzzle(5)` is 3.

User Edoloughlin
by
7.7k points