Java ProgramsPatternsPrint Diamond Number Pattern

Print Diamond Number Pattern in Java

intermediate·  Patterns  ·  Number Patterns

Problem

A number diamond is an upright number pyramid immediately followed by its inverted mirror, joined at their widest row, the same combining technique used to build a star diamond.

Given a size n, print a diamond made of repeated row numbers, n rows wide at its middle.

Input
5
Output
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 3 3 3 3 3 2 2 2 1

Java Program

Java
public class DiamondNumberPattern { static void printRow(int i, int n) { StringBuilder line = new StringBuilder(); for (int j = 1; j <= n - i; j++) line.append(' '); for (int j = 1; j <= 2 * i - 1; j++) { line.append(i); if (j < 2 * i - 1) line.append(' '); } System.out.println(line); } public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) printRow(i, n); // grow to the widest row for (int i = n - 1; i >= 1; i--) printRow(i, n); // shrink back to a point } }

Output

1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 3 3 3 3 3 2 2 2 1

Core Logic

Pulling the single-row-building logic out into its own method lets the same code print both the growing top half and the shrinking bottom half, just by calling it with row numbers running in opposite directions.

How It Works
  1. 1printRow(i, n) builds one row exactly the way the plain number pyramid does — n - i leading spaces, then the digit i repeated 2i - 1 times.
  2. 2The top half calls printRow with i from 1 to n, growing the pyramid to its widest row.
  3. 3The bottom half calls printRow with i from n - 1 back down to 1, shrinking it back to a point.
  4. 4The widest row (n) is only printed once, right at the boundary between the two halves.
For n = 5, the sequence of row numbers printed is 1, 2, 3, 4, 5, 4, 3, 2, 1 — nine rows total, each built by the same printRow call.
💡

Key Point: Starting the bottom half at n - 1, not n, is what keeps the middle row from being printed twice — the top half's last call already covers row n.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: Each of the roughly 2n rows prints a line whose length is proportional to its own row number, so the total output scales with n².

Key Concepts

nested for loophelper methodmirrored halves

Related Programs