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:
RecursiveMethods
to contain our methods.countDown
that takes an integer n
as a parameter.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.n
using System.out.println(n)
. This will print the numbers from n
down to 1.countDown
with n - 1
as the argument. This will decrement n
by 1 and continue the countdown until the base case is reached.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