Skip to main content

Command Palette

Search for a command to run...

Recursion

Published
2 min readView as Markdown

Concept

Think of recursion as a way to break down a problem into smaller, more manageable parts. In this case, we want to print the numbers from 1 to n. To achieve this using recursion, we approach the problem by thinking, "What if I could already print numbers from 1 to n-1? Then, I would just need to print n afterward."

Step-by-Step Breakdown

  1. The Recursive Insight: To print the numbers from 1 to n, you can start by printing the numbers from 1 to n-1, and then print n. This means that each time you reduce the problem by 1, you're getting closer to the base case.

  2. Base Case: The simplest version of this problem is printing just the number 1. When n is 1, you don't need to do anything more—just print 1.

     if (n == 1) {
         System.out.print(1 + " ");
         return;
     }
    
  3. Recursive Case: If n is greater than 1, you assume that you can already print the sequence from 1 to n-1, and then you just need to add n at the end.

     printNumbers(n-1);
     System.out.print(n + " ");
    
  4. How It Works: When you call printNumbers(5), the function first tries to solve printNumbers(4), but printNumbers(4) first tries to solve printNumbers(3), and this continues until the function reaches printNumbers(1), which is the base case.

  5. Unwinding the Stack: Once the base case is reached, the function starts to "unwind" or return from the recursive calls. As each function call returns, it prints the current value of n. This means the numbers are printed in ascending order.

Visualizing the Process

  • When printNumbers(5) is called, it initiates the following sequence of calls:

    • printNumbers(5) calls printNumbers(4)

    • printNumbers(4) calls printNumbers(3)

    • printNumbers(3) calls printNumbers(2)

    • printNumbers(2) calls printNumbers(1)

  • Now, starting from the base case:

    • printNumbers(1) prints 1 and returns.

    • printNumbers(2) prints 2 and returns.

    • printNumbers(3) prints 3 and returns.

    • printNumbers(4) prints 4 and returns.

    • printNumbers(5) prints 5 and returns.

Summary

  • Bottom-Up Approach: Start with the smallest problem (printing 1) and gradually add more until you reach the full problem (printing 1 to n).

  • Recursive Flow: The function keeps calling itself with a smaller value of n until it hits the base case. Then, as it returns from each recursive call, it builds the full sequence by printing the current value of n.

More from this blog

Amit singh's blog

235 posts