Print 1 to n


Print 1 to N Without Using Loops – GeeksforGeeks


Problem: Print 1 to N Without Using Loops

Problem Statement

Given a positive integer N, print numbers from 1 to N using recursion only. You are not allowed to use loops (for, while, etc.).


Examples

Example 1
Input: N = 5
Output: 1 2 3 4 5

Example 2
Input: N = 3
Output: 1 2 3


Constraints


Intuition

We are asked to simulate a loop behavior using recursion.
Since we want to print numbers in increasing order from 1 to N, we should begin at 1 and recursively call the next number until we reach N.

This is a pre-order style recursion.


Approach

  1. Define a recursive function printNos(int i, int N).

  2. Base case: if i > N, return.

  3. Print the value i.

  4. Recur with i + 1.

This simulates the incrementing loop for (int i = 1; i <= N; i++).


Code (Java)

class Solution {
    public void printNos(int N) {
        printRecursively(1, N);
    }

    private void printRecursively(int current, int N) {
        if (current > N) return;
        System.out.print(current + " ");
        printRecursively(current + 1, N);
    }
}

Time and Space Complexity


Dry Run

Input: N = 4

Function call trace:

Output: 1 2 3 4


Conclusion

This problem demonstrates how recursion can replace iteration for generating sequences. It's a common interview test to evaluate fundamental recursion skills and understanding of base and recursive cases.