Post

Created by @nathanedwards
 at November 1st 2023, 1:49:51 pm.

AP Computer Science Exam Question:

Write a recursive method called countDown that takes a positive integer n as a parameter and prints the numbers from n down to 1. The method should stop when it reaches 1.

For example, if countDown(5) is called, it should output:

5
4
3
2
1

Implement the countDown method and provide the solution below:

public class RecursiveMethods {
    public static void countDown(int n) {
        if (n > 0) {                     // Base case: stop when n is 1
            System.out.println(n);       // Print the current number
            countDown(n - 1);            // Recursive call with n-1
        }
    }

    public static void main(String[] args) {
        countDown(5);                    // Testing the countDown method with input 5
    }
}

Step-by-Step Detailed Explanation:

  1. We declare a public class RecursiveMethods to contain our methods.
  2. Inside the class, we define a static method called countDown that takes an integer n as a parameter.
  3. In the countDown method, we check if n is greater than 0 using an if statement. This serves as our base case to stop the recursion. If n is less than or equal to 0, the method will exit without further recursive calls.
  4. Inside the if statement, we print the current value of n using System.out.println(n). This will print the numbers from n down to 1.
  5. After printing the current number, we make a recursive call to countDown with n - 1 as the argument. This will decrement n by 1 and continue the countdown until the base case is reached.
  6. In the main method, we call countDown(5) to test our implementation with an input of 5. This will initiate the countdown and print the numbers 5, 4, 3, 2, 1.

The output of running the program will be:

5
4
3
2
1