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:
We start by defining the countDown method that takes an integer n as input.
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.
In the recursive case, we print the current value of n followed by a space.
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.
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.
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.