Exercise

Consider method mystery.

public static void mystery(int x)
{
    if(x >= 0)
    {
      mystery(x - 1);
      System.out.println(x);
    }
}

Which of the following describes the sequence of integers output? (Ignore line breaks.)

(A) x, x - 1, x - 2 ... 1
(B) x, x - 1, x - 2 ... 1, 0
(C) x - 1, x - 2 ... 1, 0
(D) 0, 1 ... x - 1, x
(E) 1, 2 ... x - 1, x

Solution

(D) 0, 1 ... x - 1, x

Explanation

Infinite recursion is not an answer choice, so it does not need to be considered.

The print statement is after the recursive call. It prints the original value of x. Whatever the recursive call does, the very last value that will be printed is the original value of x. This eliminates all of the answer choices except (D) and (E).

Answer choice (D) includes 0. Answer choice (E) does not. When the method is called with 0, the condition x >= 0 evaluates to true. The method prints 0. The answer is (D).

Additional notes

The base case is x < 0, the opposite of the condition in the method. Base cases must be resolved without a recursive call. It is common for base cases to be written as conditional statements at the top of a recursive method; however, this is not required.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Recursive methods with print statements