Java Tutorial
🔍

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 i from 1 to n.
  • ›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

  1. ›Draw the pattern for a small size, such as n = 4.
  2. ›Make a table with one line per row: the row number, the number of leading spaces, and the number of symbols.
  3. ›Find the formula linking each column of the table to i (and n).
  4. ›Write the outer loop for rows, and one inner loop per formula.
  5. ›Test with n = 1 and n = 2 — small sizes expose off-by-one errors quickly.

Example 1: Right Triangle

* * * * * * * * * *
Row iSpacesStars
101
202
303
404

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 iSpacesStars
131
223
315
407

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.

Show all 40 practice programs ↓
Patternsintermediate
Print Alphabet Diamond

Prints a diamond built from repeating letters by joining a pyramid to its own mirror image.

Patternsintermediate
Print Alphabet Pyramid

Prints a centered pyramid where every row is filled with a single repeating letter.

Patternsbeginner
Print Binary Triangle

Prints a triangle where every number in a row is that row's own parity bit.

Patternsbeginner
Print Character Triangle

Prints a left-aligned triangle built from consecutive alphabet letters instead of stars.

Patternsadvanced
Print Concentric Number Pattern

Fills an n x n grid so each concentric ring of cells shares the same number.

Patternsbeginner
Print Continuous Number Pattern

Fills a fixed-size grid with consecutive numbers that keep counting up across every row.

Patternsintermediate
Print Diamond Number Pattern

Prints a diamond shape built from repeated row numbers instead of stars.

Patternsintermediate
Print Hollow Diamond

Prints a diamond outline made of stars, hollow all the way through.

Patternsintermediate
Print Hollow Rectangle

Prints a rectangle outline made of stars, hollow on the inside.

Patternsintermediate
Print Hollow Rhombus

Prints the outline of a slanted parallelogram, leaving its interior empty.

Patternsintermediate
Print Hollow Triangle

Prints a left-aligned triangle outline, hollow except for a solid base.

Patternsintermediate
Print Hourglass Pattern

Prints a wide-narrow-wide star shape by joining an inverted triangle to a regular one.

Patternsintermediate
Print Inverted Alphabet Pyramid

Prints a centered pyramid of repeating letters upside down, widest row first.

Patternsintermediate
Print Inverted Number Pyramid

Prints a centered pyramid of repeated row numbers, upside down with its apex at the bottom.

Patternsbeginner
Print Inverted Number Triangle

Prints a left-aligned triangle whose row width shrinks, while each row still counts up from 1.

Patternsbeginner
Print Inverted Right Triangle

Prints a left-aligned triangle of stars that shrinks by one star per row.

Patternsbeginner
Print Inverted Triangle

Prints a left-aligned shrinking star triangle by building each row as one string, without a separate inner loop.

Patternsbeginner
Print Left-Aligned Triangle

Prints a left-aligned growing star triangle by building each row as one string, without a separate inner loop.

Patternsintermediate
Print Multiplication Triangle

Prints a growing triangle where each row shows that row number's own multiplication table.

Patternsbeginner
Print Number Triangle

Prints a left-aligned triangle where each row counts up from 1.

Patternsintermediate
Print Plus Pattern

Prints stars forming a plus sign across a square grid, using the middle row and column.

Patternsbeginner
Print Rectangle Star Pattern

Prints a solid grid of stars with a separate row count and column count.

Patternsbeginner
Print Repeated Number Pattern

Prints a left-aligned triangle where each row repeats its own row number that many times.

Patternsintermediate
Print Rhombus Pattern

Prints a slanted parallelogram of stars using increasing indentation per row.

Patternsadvanced
Print Spiral Number Pattern

Fills an n x n grid with numbers 1 through n squared in clockwise spiral order.

Patternsbeginner
Print Square Star Pattern

Prints a solid square grid of stars, n rows by n columns.

Patternsadvanced
Print Wave Pattern

Prints a wavy line of stars that rises to a peak and dips to a trough as it crosses the columns.

Patternsintermediate
Print X Pattern

Prints stars forming the letter X across a square grid, using both diagonals.

Patternsbeginner
Print 0-1 Triangle

Prints a triangle where each position alternates between 0 and 1 in a checkerboard pattern.

Patternsadvanced
Print Zig-Zag Pattern

Prints a three-row zigzag line of stars that travels up and down across the columns.

Browse all Java programs →