Java Program to Print Pyramid Pattern
for loops where the outer loop controls the rows and the inner loops print spaces and stars, like for (int i = 1; i <= n; i++) { for (int j = n; j > i; j--) System.out.print(" "); for (int k = 1; k <= 2*i-1; k++) System.out.print("*"); System.out.println(); }.Examples
How to Think About It
Algorithm
Code
public class PyramidPattern { public static void main(String[] args) { int n = 5; // number of rows for (int i = 1; i <= n; i++) { for (int j = n; j > i; j--) { System.out.print(" "); } for (int k = 1; k <= 2 * i - 1; k++) { System.out.print("*"); } System.out.println(); } } }
Dry Run
Let's trace n=3 through the code
Row 1
Print 2 spaces, then 1 star: ' *'
Row 2
Print 1 space, then 3 stars: ' ***'
Row 3
Print 0 spaces, then 5 stars: '*****'
| Row (i) | Spaces (n - i) | Stars (2*i - 1) |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 1 | 3 |
| 3 | 0 | 5 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration prints one row of the pyramid.
Step 2: Print spaces before stars
The first inner loop prints spaces to align stars in a pyramid shape, decreasing as row number increases.
Step 3: Print stars for pyramid
The second inner loop prints stars, increasing by two each row to form the pyramid shape.
Alternative Approaches
public class PyramidPattern { public static void main(String[] args) { int n = 5; int i = 1; while (i <= n) { int j = n; while (j > i) { System.out.print(" "); j--; } int k = 1; while (k <= 2 * i - 1) { System.out.print("*"); k++; } System.out.println(); i++; } } }
public class PyramidPattern { public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) { System.out.print(" ".repeat(n - i)); System.out.print("*".repeat(2 * i - 1)); System.out.println(); } } }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops: the outer loop runs n times and inner loops run up to n times, resulting in O(n^2) time.
Space Complexity
Only a few variables are used; no extra space proportional to input size, so space complexity is O(1).
Which Approach is Fastest?
Using String.repeat() is concise but similar in performance; while loops are less readable but equivalent in speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Readability and clarity |
| While loops | O(n^2) | O(1) | When for loops are unfamiliar |
| String.repeat() | O(n^2) | O(1) | Concise code with Java 11+ |