Print Numbers Using Recursion in Java
beginner· Recursion · Recursion
Problem
A recursive call can stand in for a loop's counter — each call handles one number, then hands off to the next call before returning.
Given a number n, print every integer from 1 to n using recursion.
Input
n = 5
Output
1
2
3
4
5
Java Program
Java
public class PrintNumbersRecursion {
static void print(int i, int n) {
if (i > n) return; // every number up to n has been printed
System.out.println(i);
print(i + 1, n);
}
public static void main(String[] args) {
int n = 5;
print(1, n);
}
}Output
1
2
3
4
5
Core Logic
Printing the current number and then recursing on the next one, before doing anything else, prints the whole sequence in order without any loop.
How It Works
- 1
print(i, n)takes the current numberiand the upper boundn. - 2The base case
if (i > n) return;stops the recursion once every number has been printed. - 3Each call prints
ifirst, then callsprint(i + 1, n)to handle the next number. - 4The initial call
print(1, n)starts the sequence at 1.
For
n = 5, the calls print 1, 2, 3, 4, 5 in order, each call printing before recursing further.💡
Key Point: Printing happens before the recursive call here, so the numbers appear in ascending order exactly as each call runs — nothing waits until the recursion unwinds.
Complexity
Time Complexity: O(n)Space Complexity: O(n)
Why: One recursive call handles each number printed, and the call stack grows to depth n before the base case is reached and the frames start returning.
Key Concepts
recursionbase casecall before return