Post

Created by @nathanedwards
 at November 1st 2023, 3:57:39 pm.

Question:

A recursive method named printNumbers is defined below. The method takes an integer parameter n and prints all the numbers from 1 to n in increasing order.

public void printNumbers(int n) {
   if (n <= 0) {
      return;
   }
   printNumbers(n-1);
   System.out.print(n + " ");
}

Using the provided method, write a Java program to print all the numbers from 1 to n in decreasing order using recursion.

Write a recursive method named printNumbersDescending that takes an integer parameter n and prints all the numbers from n to 1 in decreasing order.

Signature:

public void printNumbersDescending(int n)

Example:

printNumbersDescending(5);

Output:

5 4 3 2 1

Write the implementation of the printNumbersDescending method that fulfills the given requirements.

Explanation:

The recursion works by first checking the base case (when n <= 0). If the base case is true, the recursion stops. Otherwise, it calls itself with n-1 to move closer to the base case.

In this specific case, printNumbers(n-1) is called before printing the number n. This ensures the numbers are printed in the desired order.

The method printNumbersDescending simply updates the method call order to achieve the desired result. Instead of calling printNumbers before printing the number, it needs to print the number first and then call printNumbersDescending with n-1.

Answer:

public class Main {
   public static void main(String[] args) {
      printNumbersDescending(5);
   }
   
   public static void printNumbersDescending(int n) {
      if (n <= 0) {
         return;
      }
      
      System.out.print(n + " ");
      printNumbersDescending(n-1);
   }
}

The output of the above code will be 5 4 3 2 1 as expected.