Print 1 to n
Problem Link
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
1 <= N <= 10⁴
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
-
Define a recursive function
printNos(int i, int N). -
Base case: if
i > N, return. -
Print the value
i. -
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
-
Time Complexity:
O(N)- Each recursive call processes one number from 1 to N.
-
Space Complexity:
O(N)(due to recursion stack)
Dry Run
Input: N = 4
Function call trace:
-
printRecursively(1, 4)→ prints 1 → callsprintRecursively(2, 4) -
printRecursively(2, 4)→ prints 2 → callsprintRecursively(3, 4) -
printRecursively(3, 4)→ prints 3 → callsprintRecursively(4, 4) -
printRecursively(4, 4)→ prints 4 → callsprintRecursively(5, 4) -
printRecursively(5, 4)→ returns (base case)
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.