Java Program to Print Number Pattern
for loops; for example, for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(); } prints numbers from 1 up to the current line number.Examples
How to Think About It
Algorithm
Code
public class NumberPattern { public static void main(String[] args) { int n = 5; // number of lines for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(); } } }
Dry Run
Let's trace n=3 through the code
Start outer loop i=1
Inner loop runs j=1; prints '1 '
Print newline after inner loop
Output so far: 1
Outer loop i=2
Inner loop runs j=1, j=2; prints '1 2 '
Print newline after inner loop
Output so far: 1 1 2
Outer loop i=3
Inner loop runs j=1, j=2, j=3; prints '1 2 3 '
Print newline after inner loop
Output so far: 1 1 2 1 2 3
| i (line) | j (number printed) | Output line |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 2 | 1 2 |
| 3 | 1 2 3 | 1 2 3 |
Why This Works
Step 1: Outer loop controls lines
The outer for loop runs from 1 to n, controlling how many lines are printed.
Step 2: Inner loop prints numbers
The inner for loop runs from 1 to the current line number i, printing numbers in sequence.
Step 3: New line after each row
After printing numbers for a line, System.out.println() moves the cursor to the next line.
Alternative Approaches
public class NumberPattern { public static void main(String[] args) { int n = 5; int i = 1; while (i <= n) { int j = 1; while (j <= i) { System.out.print(j + " "); j++; } System.out.println(); i++; } } }
public class NumberPattern { public static void main(String[] args) { int n = 5; for (int i = n; i >= 1; i--) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(); } } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops cause the program to run in O(n^2) time because for each line i, it prints i numbers.
Space Complexity
The program uses constant extra space O(1) as it only prints output and uses a few variables.
Which Approach is Fastest?
All approaches have similar O(n^2) time; using for loops is more concise and readable than while loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and readable pattern printing |
| Nested while loops | O(n^2) | O(1) | When loop conditions are dynamic or less predictable |
| Reverse pattern with for loops | O(n^2) | O(1) | Printing patterns in descending order |