Java Program to Print Star Pattern
for loops; for example, for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } prints a right-angled triangle of stars.Examples
How to Think About It
Algorithm
Code
public class StarPattern { public static void main(String[] args) { int n = 5; // number of rows for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } }
Dry Run
Let's trace the star pattern printing for n = 3 through the code
Initialize n
n = 3
First outer loop iteration (i=1)
Inner loop runs j=1; prints '*' once; then prints newline
Second outer loop iteration (i=2)
Inner loop runs j=1 to 2; prints '**'; then prints newline
Third outer loop iteration (i=3)
Inner loop runs j=1 to 3; prints '***'; then prints newline
| i (row) | Stars printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration representing one row.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number, printing stars on the same line.
Step 3: New line after each row
After printing stars for a row, System.out.println() moves the cursor to the next line.
Alternative Approaches
public class StarPattern { 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++; } System.out.println(); i++; } } }
public class StarPattern { public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) { System.out.println("*".repeat(i)); } } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops cause the program to print stars in a triangular pattern, resulting in about n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The program uses a fixed amount of extra space regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Using String.repeat can be more concise but internally still runs in O(n^2) time; all approaches have similar performance for this simple pattern.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clear and beginner-friendly |
| Nested while loops | O(n^2) | O(1) | Alternative loop style |
| String.repeat (Java 11+) | O(n^2) | O(1) | Concise code with modern Java |