Post

Created by @nathanedwards
 at November 1st 2023, 4:35:07 am.

Question:

Write a Java method called printNumbers that takes an integer n as input and recursively prints all the numbers from n down to 1. The method should print all the numbers on separate lines.

Signature:

public static void printNumbers(int n)

Example:

printNumbers(5) should print:
5
4
3
2
1

printNumbers(10) should print:
10
9
8
7
6
5
4
3
2
1

Implement the printNumbers method using recursion.

Answer:

public class RecursiveThinking {
    
    public static void main(String[] args) {
        // Testing the method
        System.out.println("Printing numbers from 5 to 1:");
        printNumbers(5);
        
        System.out.println("\nPrinting numbers from 10 to 1:");
        printNumbers(10);
    }
    
    public static void printNumbers(int n) {
        if (n <= 0) {
            // Base case: When n becomes less than or equal to 0
            return;
        } else {
            // Recursive case: Print the current number,
            // then call the method with the next number (n-1)
            System.out.println(n);
            printNumbers(n - 1);
        }
    }
}

Step-by-step Explanation:

  1. The printNumbers method takes an integer n as input.

  2. If n is less than or equal to 0, it means we have reached the base case of the recursion and we stop the recursive calls. Hence, we simply return from the method.

  3. Otherwise, for all other values of n, the recursive case is executed. First, we print the current number n using the System.out.println() method. Then, we make a recursive call to printNumbers by passing the next number (n-1) as the argument. This recursive call repeats until n becomes less than or equal to 0.

  4. The recursion ends when the method is called with n equal to 0. At this point, the recursive calls stop and the execution returns back to the previous call. Each previous call then proceeds to print the corresponding number and returns, until we reach the initial invocation of the method.

  5. Lastly, we test the printNumbers method by calling it with different inputs (5 and 10) in the main method. The expected output is displayed using the System.out.println() method.