Post

Created by @nathanedwards
 at November 3rd 2023, 8:17:35 am.

Question:

Write a recursive method printNumbers that takes an integer n as a parameter and prints the numbers from 1 to n in ascending order. The method should not use any loops or iteration.

Signature:

public void printNumbers(int n)

Example:

printNumbers(5)

Output:

1 2 3 4 5

Explanation:

The method printNumbers recursively calls itself with the new parameter n-1 until n becomes 0. On each recursive call, we print the current value of n, and then make another recursive call with the new parameter n-1. This continues until n becomes 0, at which point the recursion ends and the method returns.

The steps involved are as follows:

  1. printNumbers(5) - prints "5" and calls printNumbers(4)
  2. printNumbers(4) - prints "4" and calls printNumbers(3)
  3. printNumbers(3) - prints "3" and calls printNumbers(2)
  4. printNumbers(2) - prints "2" and calls printNumbers(1)
  5. printNumbers(1) - prints "1" and calls printNumbers(0)
  6. printNumbers(0) - base case reached, recursion ends, nothing is printed and the method returns.

So, the numbers are printed in ascending order: 5 4 3 2 1.

public void printNumbers(int n) {
   // Base case: when n is 0, return
   if (n == 0) {
       return;
   }
   
   // Recursive case: print n and call printNumbers with n-1
   printNumbers(n-1);
   System.out.print(n + " ");
}

Complexity Analysis:

  • The time complexity of the printNumbers method is O(n) because we are making n recursive calls, and each call takes O(1) time.
  • The space complexity is O(n) because the call stack can hold at most n recursive calls.