Print Diamond Number Pattern in Java
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.
Java Program
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
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.
- 1
printRow(i, n)builds one row exactly the way the plain number pyramid does —n - ileading spaces, then the digitirepeated2i - 1times. - 2The top half calls
printRowwithifrom1ton, growing the pyramid to its widest row. - 3The bottom half calls
printRowwithifromn - 1back down to1, shrinking it back to a point. - 4The widest row (
n) is only printed once, right at the boundary between the two halves.
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.
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².