Java Pattern Printing Programs Explained
Java Pattern Printing
Pattern programs — triangles, pyramids and diamonds made of stars or numbers — look like puzzles, but nearly all of them are solved with the same method. Once you can describe a single row with a formula, the code almost writes itself. That's why they're a favourite way to practise nested loops, and a common warm-up in coding interviews.
The Core Idea: Rows and Columns
Every pattern is printed one row at a time, from top to bottom. That gives a fixed structure:
- ›The outer loop chooses the row, usually
ifrom 1 ton. - ›One or more inner loops print what belongs on that row — typically some spaces, then some symbols.
- ›After the inner loops, a line break moves to the next row.
The only real work is answering one question for every pattern: for row i, how many spaces and how many symbols are needed? Once those two numbers are written as formulas in i and n, the code follows directly.
Step-by-Step Method
- ›Draw the pattern for a small size, such as
n = 4. - ›Make a table with one line per row: the row number, the number of leading spaces, and the number of symbols.
- ›Find the formula linking each column of the table to
i(andn). - ›Write the outer loop for rows, and one inner loop per formula.
- ›Test with
n = 1andn = 2— small sizes expose off-by-one errors quickly.
Example 1: Right Triangle
*
* *
* * *
* * * *
Row i | Spaces | Stars |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 0 | 2 |
| 3 | 0 | 3 |
| 4 | 0 | 4 |
Row i has i stars and no leading spaces:
1public class RightTriangle {
2 public static void main(String[] args) {
3 int n = 4;
4 for (int i = 1; i <= n; i++) { // one iteration per row
5 for (int j = 1; j <= i; j++) { // i stars on row i
6 System.out.print("* ");
7 }
8 System.out.println(); // end the row
9 }
10 }
11}Example 2: Centered Pyramid
*
***
*****
*******
Row i | Spaces | Stars |
|---|---|---|
| 1 | 3 | 1 |
| 2 | 2 | 3 |
| 3 | 1 | 5 |
| 4 | 0 | 7 |
Spaces fall by one per row, so they're n - i. Stars grow by two per row, starting at 1, so they're 2 * i - 1.
1public class CenteredPyramid {
2 public static void main(String[] args) {
3 int n = 4;
4 for (int i = 1; i <= n; i++) {
5 StringBuilder row = new StringBuilder();
6 for (int s = 1; s <= n - i; s++) row.append(' '); // leading spaces
7 for (int k = 1; k <= 2 * i - 1; k++) row.append('*'); // stars
8 System.out.println(row);
9 }
10 }
11}Building each row in a StringBuilder and printing it once is faster than many separate print calls, which matters for large patterns.
Example 3: Inverted Patterns
To turn a pattern upside down, keep the same formulas and run the outer loop backwards — from n down to 1. For the inverted pyramid, row i still has n - i spaces and 2 * i - 1 stars; only the order of the rows changes.
A diamond is simply a pyramid followed by an inverted pyramid that skips its widest row, so the middle line isn't printed twice:
1public class Diamond {
2 static void printRow(int n, int i) {
3 System.out.println(" ".repeat(n - i) + "*".repeat(2 * i - 1)); // String.repeat: Java 11+
4 }
5
6 public static void main(String[] args) {
7 int n = 3;
8 for (int i = 1; i <= n; i++) printRow(n, i); // top half, including the middle
9 for (int i = n - 1; i >= 1; i--) printRow(n, i); // bottom half, without the middle
10 }
11}Output:
*
***
*****
***
*
Example 4: Number Patterns
Number patterns use the same loops but print a value instead of a star. The value is usually one of three things:
- ›The column number
j— every row counts up from 1:1,1 2,1 2 3. - ›The row number
i— every row repeats one number:1,2 2,3 3 3. - ›A counter that never resets — the numbers keep climbing across rows, as in Floyd's triangle:
1,2 3,4 5 6.
1public class FloydsTriangle {
2 public static void main(String[] args) {
3 int n = 4;
4 int number = 1; // declared outside the loops, so it never resets
5 for (int i = 1; i <= n; i++) {
6 StringBuilder row = new StringBuilder();
7 for (int j = 1; j <= i; j++) {
8 row.append(number++).append(' ');
9 }
10 System.out.println(row.toString().trim());
11 }
12 }
13}Output:
1
2 3
4 5 6
7 8 9 10
Example 5: Hollow Shapes
Hollow patterns print a symbol only on the border and a space everywhere else. Loop over every position as usual, then use a condition to decide what goes there.
1public class HollowSquare {
2 public static void main(String[] args) {
3 int n = 5;
4 for (int i = 1; i <= n; i++) {
5 StringBuilder row = new StringBuilder();
6 for (int j = 1; j <= n; j++) {
7 boolean border = i == 1 || i == n || j == 1 || j == n; // first/last row or column
8 row.append(border ? '*' : ' ');
9 }
10 System.out.println(row);
11 }
12 }
13}Output:
*****
* *
* *
* *
*****
The same trick works for hollow triangles and pyramids: print the symbol only when it's the first or last position on the row, or anywhere on the bottom row.
Common Mistakes
Mistake 1 — Forgetting the Line Break
If System.out.println() is missing after the inner loop, every row prints on the same line. Keep the row's output and the line break clearly separated: inner loops build the row, and the outer loop ends it.
Mistake 2 — Off-by-One in the Star Count
Writing j < i instead of j <= i prints one symbol too few on every row, so the first row comes out empty. Test with n = 1 — it should print exactly one symbol.
Mistake 3 — Resetting a Counter Inside the Loop
In Floyd's triangle, declaring int number = 1; inside the outer loop restarts the count on every row, producing 1, 1 2, 1 2 3 instead. Decide whether a counter belongs to the whole pattern or to a single row, and declare it at that level.
Mistake 4 — Mixing "* " and "*" with the Wrong Space Count
A star followed by a space takes two columns. If you print "* " for symbols, the leading spaces for centering must be adjusted too, or the pattern leans to one side. Pick one style per pattern and derive the formulas for it.
Interview Questions
How do you approach a pattern program you've never seen before?
Draw it for a small size, tabulate spaces and symbols for each row, find the formulas in terms of the row number, then write one inner loop per formula. Most patterns need no more than two inner loops.
What is the time complexity of printing a pyramid with n rows?
O(n²). Row i prints about 2i characters, and adding those up over n rows gives roughly n² characters in total.
How do you print a pattern without nested loops?
From Java 11, " ".repeat(k) + "*".repeat(m) builds a whole row in one expression, leaving only the outer loop. The work is the same; the inner loops are just hidden inside repeat.
FAQs
Why do pattern programs start the row counter at 1 instead of 0?
Starting at 1 makes formulas like "row i has i stars" read naturally. Starting at 0 works too, but every formula shifts by one, for example i + 1 stars.
How do I print a pattern of letters?
Use a char and add to it: (char) ('A' + j - 1) gives A, B, C … across a row. The loops stay exactly the same as for numbers.
Should I use print or StringBuilder?
For small patterns either is fine. For large ones, building each row in a StringBuilder and printing it once is noticeably faster, because console output is slow.
Summary
Pattern printing is nested-loop practice in disguise. The outer loop picks the row, the inner loops print that row's spaces and symbols, and everything hinges on writing those two counts as formulas in the row number. Inverted patterns reverse the outer loop, diamonds combine two halves, number patterns change what is printed, and hollow shapes add a border condition. Work through the practice programs below to see each technique applied.
What to Read Next
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Prints a centered pyramid of stars, apex at the top.
Prints a left-aligned triangle of stars that grows by one star per row.
Prints a diamond of stars by stacking a pyramid on top of an inverted pyramid.
Prints a triangle of consecutive numbers that never resets between rows.
Prints a square outline of stars, hollow on the inside.
Prints a centered pyramid where every row is filled with that row's own number.
Prints a centered pyramid of stars turned upside down, apex at the bottom.
Prints Pascal's triangle centered, so its outline reads as an actual triangle shape.
Prints a butterfly-shaped star pattern using two mirrored triangular wings.
Prints a centered pyramid outline, hollow except for a solid base.
Show all 40 practice programs ↓Show fewer ↑
Prints a diamond built from repeating letters by joining a pyramid to its own mirror image.
Prints a centered pyramid where every row is filled with a single repeating letter.
Prints a triangle where every number in a row is that row's own parity bit.
Prints a left-aligned triangle built from consecutive alphabet letters instead of stars.
Fills an n x n grid so each concentric ring of cells shares the same number.
Fills a fixed-size grid with consecutive numbers that keep counting up across every row.
Prints a diamond shape built from repeated row numbers instead of stars.
Prints a diamond outline made of stars, hollow all the way through.
Prints a rectangle outline made of stars, hollow on the inside.
Prints the outline of a slanted parallelogram, leaving its interior empty.
Prints a left-aligned triangle outline, hollow except for a solid base.
Prints a wide-narrow-wide star shape by joining an inverted triangle to a regular one.
Prints a centered pyramid of repeating letters upside down, widest row first.
Prints a centered pyramid of repeated row numbers, upside down with its apex at the bottom.
Prints a left-aligned triangle whose row width shrinks, while each row still counts up from 1.
Prints a left-aligned triangle of stars that shrinks by one star per row.
Prints a left-aligned shrinking star triangle by building each row as one string, without a separate inner loop.
Prints a left-aligned growing star triangle by building each row as one string, without a separate inner loop.
Prints a growing triangle where each row shows that row number's own multiplication table.
Prints a left-aligned triangle where each row counts up from 1.
Prints stars forming a plus sign across a square grid, using the middle row and column.
Prints a solid grid of stars with a separate row count and column count.
Prints a left-aligned triangle where each row repeats its own row number that many times.
Prints a slanted parallelogram of stars using increasing indentation per row.
Fills an n x n grid with numbers 1 through n squared in clockwise spiral order.
Prints a solid square grid of stars, n rows by n columns.
Prints a wavy line of stars that rises to a peak and dips to a trough as it crosses the columns.
Prints stars forming the letter X across a square grid, using both diagonals.
Prints a triangle where each position alternates between 0 and 1 in a checkerboard pattern.
Prints a three-row zigzag line of stars that travels up and down across the columns.