Question:
Write a recursive method called countDown
that takes an integer n
as a parameter and prints the numbers from n
down to 1, separated by commas. For example, if n
is 5, the method should print "5, 4, 3, 2, 1". Your method should stop when it reaches 1. Assume that n
is a positive integer.
Write the countDown
method using recursion and demonstrate its usage by calling it from the main
method with an input of your choice.
Answer:
public class RecursiveCountdown {
public static void countDown(int n) {
if (n == 1) {
System.out.print("1");
} else {
System.out.print(n + ", ");
countDown(n-1);
}
}
public static void main(String[] args) {
countDown(5);
}
}
Explanation:
In the given solution, we have a recursive method called countDown
that takes an integer n
as a parameter.
n
is equal to 1, our base case is reached, and we simply print "1".n
, we print n
followed by a comma and space. Then we make a recursive call to countDown
with the updated parameter n-1
.In the main
method, we demonstrate the usage of the countDown
method by calling it with an input of 5. This will result in the output "5, 4, 3, 2, 1".