Post

Created by @nathanedwards
 at November 4th 2023, 6:04:36 pm.

Exam Question:

Write a recursive method called countDown that takes an integer n as input and prints the numbers from n to 1 in descending order. For example, if n is 5, the method should print: 5 4 3 2 1.

Solution:

The recursive method countDown can be implemented as follows:

public class RecursiveMethods {
    
    public static void countDown(int n) {
        // Base case: if n is less than 1, return
        if (n < 1) {
            return;
        }
        
        // Print the current number
        System.out.print(n + " ");
        
        // Recursive call with (n - 1) as the new input
        countDown(n - 1);
    }
    
    public static void main(String[] args) {
        int n = 5;
        System.out.print("Countdown: ");
        countDown(n);
    }
}

Step-by-step Explanation:

  1. We start by defining the countDown method that takes an integer n as input.

  2. The base case for this recursive method is when n is less than 1. In this case, we simply return from the method without performing any further operations.

  3. In the recursive case, we print the current value of n followed by a space.

  4. After printing the current number, we make a recursive call to countDown with the new input as n - 1. This ensures that the method is called again with a smaller value of n.

  5. Finally, in the main method, we initialize a variable n with a value of 5. We then call the countDown method with n as the input.

  6. The output of running the code will be:

Countdown: 5 4 3 2 1

This output shows that the countDown method is recursively printing the numbers from n to 1 in descending order.