Centered Number Diamond Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Mirror

What You’ll Learn

The centered number diamond prints 1, then 123, then 12345, and so on — then mirrors back down to 1. This tutorial covers the top and bottom halves, digit loops, live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Odd-width rows

Row i prints digits 1..(2*i-1) concatenated; leading spaces center each row.

Space Loop

Center rows

for (j = i; j < rows; j++) prints leading spaces before digits.

Digit Loop

1..2*i-1

System.out.print(k) for k = 1..2*i-1 — concatenated digits per row.

Mirror Loop

Bottom half

for (i = rows-1; i >= 1; i--) repeats the same row logic downward.

Live Preview

1–20 rows

Pick a row count and draw the centered number diamond instantly in the browser.

O(n²)

Complexity

Prints odd-width rows mirrored across n rows — iterations; extra memory stays O(1).

Introduction

A centered number diamond prints 1, then 123, then 12345, up to the widest row, then mirrors back down. With rows = 5, the middle line is 123456789.

In Java you use a top-half loop (i = 1..rows), leading spaces, and a digit loop (k = 1..2*i-1), then a bottom-half loop mirrors the same logic with i = rows-1..1.

Why it matters?

It combines centering spaces with a mirrored second loop — the classic two-triangle diamond pattern.

Key Highlights

Top + Bottom Halves

Grow with i = 1..rows, then mirror with i = rows-1..1.

Leading Spaces

rows - i spaces center each row in the diamond.

Concatenated Digits

Each row prints 1, 123, 12345, … without separators.

Series Foundation

Follow Program 43 right-aligned triangle; continue to Program 45 star cross pattern.

In short: top half grows odd-width digit rows with leading spaces; bottom half mirrors the same logic; call System.out.println() after each row.

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print a centered number diamond: odd-width digit rows grow to the middle, then mirror downward.

Java
// rows = 5 (conceptual shape)
//     1
//    123
//   12345
//  1234567
// 123456789
//  1234567
//   12345
//    123
//     1

Inputs & Outputs

ItemTypeDescription
rowsintHeight of the top half (and widest row index).
Printed outputtextCentered diamond of concatenated digits; 2*rows - 1 total lines.

Minimal workflow

Pseudocode
for i from 1 to rows (top half):
    print (rows - i) spaces
    for k from 1 to 2*i-1: print k
    print newline
for i from rows-1 down to 1 (bottom half):
    print (rows - i) spaces
    for k from 1 to 2*i-1: print k
    print newline

Approach comparison

ApproachIdeaBest for
Top + bottom halvesLeading spaces, then digits 1..2*i-1Learning and interviews
User-input sizesc.nextInt();Flexible console programs
Spaced-digit diamondPrint k + " " between digitsMore readable output

⚡ Quick Reference

GoalPattern
Space loopfor (j = i; j < rows; j++) (top) or j = rows; j > i; j-- (bottom)
Top halffor (i = 1; i <= rows; i++)
Bottom half mirrorfor (i = rows-1; i >= 1; i--)
Digit loopfor (k = 1; k < i * 2; k++) + print(k)
End the rowSystem.out.println();
Program 43 contrastRight-aligned triangle grows one way; this pattern mirrors rows after the widest line

📋 Top Half vs Bottom Half vs Combined

Same diamond row — how centering spaces and concatenated digits work together.

Top half
i = 1..rows

Growing half — widest row at i = rows

Bottom half
i = rows-1..1

Mirrors top half after the middle row

Digit loop
k = 1..2*i-1

Prints 1, 123, 12345, … concatenated

Learning tip
trace i=3

Dry-run row 3: two spaces then 12345

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetry — two mirrored loop halves with centering spaces.

  1. First lab exercise

    Classic follow-up after right-aligned triangles and pyramids.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible row count.

  4. Gateway to variants

    Compare with Program 43 (right-aligned triangle), then continue to Program 45 (star cross).

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the centered number diamond in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed row count, Scanner input, and a spaced-digit variant. Click View Output to reveal sample console results.

📚 Getting Started

Print a full diamond with top and bottom loop pairs.

Example 1 — Fixed rows = 5

Hard-coded size — top half grows, bottom half mirrors each row.

Java
public class NumberDiamondPattern {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j < rows; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k < i * 2; k++) {
                System.out.print(k);
            }
            System.out.println();
        }

        for (int i = rows - 1; i >= 1; i--) {
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            for (int k = 1; k < i * 2; k++) {
                System.out.print(k);
            }
            System.out.println();
        }
    }
}

How It Works

When i = 1, four leading spaces precede a single 1. When i = 3, two spaces precede 12345 — odd-width rows build the diamond shape.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the row count with Scanner.nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class NumberDiamondPatternInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j < rows; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k < i * 2; k++) {
                System.out.print(k);
            }
            System.out.println();
        }

        for (int i = rows - 1; i >= 1; i--) {
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            for (int k = 1; k < i * 2; k++) {
                System.out.print(k);
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() for safer labs.

⚡ Readability Variant

Add spaces between digits for a more readable diamond.

Example 3 — Spaced-Digit Diamond

Print a space after each digit for a more readable centered diamond.

Java
public class SpacedNumberDiamond {
    public static void main(String[] args) {
        int rows = 3;

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j < rows; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k < i * 2; k++) {
                System.out.print(k + " ");
            }
            System.out.println();
        }

        for (int i = rows - 1; i >= 1; i--) {
            for (int j = rows; j > i; j--) {
                System.out.print("  ");
            }
            for (int k = 1; k < i * 2; k++) {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

How It Works

Same two-loop structure; print(k + " ") adds spacing between digits and wider indent pairs keep centering.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set rows (fixed or from input).

Setup
2

Outer loop (rows)

for (i = 1; i <= rows; i++) — walks the growing top half of the diamond.

Row
3

Space loop (center)

for (j = i; j < rows; j++) prints leading spaces before digits.

Spaces
4

Bottom half (mirror)

for (i = rows-1; i >= 1; i--) repeats the same row logic downward.

Mirror
=

Centered number diamond complete

Total digits printed grow on the order of O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5, top-half row i = 3

Trace one growing row before the mirror loop runs.

StepLoopPrints
Spacesj = 3, 4 (2 times)
Digitsk = 1..512345

Row output: 12345 — full diamond has 2*rows - 1 lines when the bottom half mirrors the top.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: skip the bottom half and get a pyramid instead of a diamond.

2. Pattern Series Base

Foundation for number diamonds, centered pyramids, and mirrored patterns.

Example: swap digits for stars to build a star diamond variant.

3. Console Formatting Drills

Practice System.out.print vs row newline without complex math.

Example: put System.out.println() inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: print 1, 12, 123 without spaces between digits.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count output lines for n = 5 → 9 (2*5-1).

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner Java courses.

  1. 1. Instant Visual Feedback

    Wrong loop bounds show up immediately as a lopsided or off-center diamond.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, left-align, or swap digits for stars with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the two-loop diamond first; then try the spaced-digit variant in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer Scanner

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Use Ternary for Compact Code

    One-liner for spaces: System.out.print(" ".repeat(rows - i)); before the digit loop.

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of digits per line, you almost certainly put System.out.println() inside the inner loop.

Common Pitfalls

Mistakes that commonly break centered number diamonds.

  1. 1. System.out.println() Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a diamond.

    → Use System.out.print for spaces and numbers; System.out.println() only after both inner loops.

  2. 2. Forgetting the Bottom Half

    Printing only the top loop gives a pyramid, not a full diamond.

    → Add for (i = rows-1; i >= 1; i--) after the top-half loop.

  3. 3. Forgetting the Row Break

    Omitting System.out.println() glues every row onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw InputMismatchException.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Wrong Digit Bound

    Using k <= i instead of k < i * 2 prints too few digits per row.

    → Keep for (k = 1; k < i * 2; k++) for odd-width rows 1, 3, 5, …

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is one centered 1 on a single line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as odd-width rows mirrored plus spaces — fine for labs, noisy for huge n.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves rows unset — call sc.hasNextInt() first.

Fill char

Spaced-digit diamond

Print k + " " between digits — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Star cross pattern

  • X shape with a middle column of stars
  • Continue with Program 45

2. Palindromic row diamond

  • Print 1 2 3 2 1 on each row instead of 12345
  • Keep the same centering spaces

3. Alphabet diamond

  • Replace digits with letters A, B, C, …
  • Same top and bottom loop structure

4. Spaced digits

  • Use print(k + " ") like Example 3
  • Widen indent pairs to " " when needed

Notes

  • Digit count. Widest row prints 2*rows-1 digits; the full diamond has 2*rows-1 lines.
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print one indented 1.
  • Use System.out.print(k) to concatenate digits; add spaces in Example 3 when readability matters.

Quick Takeaway: top half grows odd-width rows, bottom half mirrors, leading spaces center each line, then break the row.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Spaced-digit diamond (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The centered number diamond combines nested loops with a simple mirror pattern — a natural step after right-aligned triangles. Master the fixed-rows version first, then try user input and the spaced-digit diamond.

Practice the three examples above, then continue to Program 45 for the star cross pattern with 0s.

Every row prints 2*i-1 digits — keep println() only after both inner loops finish.

💡 Best Practices

✅ Do

  • Explain top half, bottom mirror, and digit loop before coding
  • Use print(k) and println() after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call System.out.println() inside the inner digit loop
  • Skip the bottom half (you get a pyramid, not a diamond)
  • Use k <= i instead of k < i * 2
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this centered number diamond

Print the pattern the beginner-friendly way.

5
Core concepts
02

Top half

2*i-1 digits

Code
03

Bottom half

Mirror i down

Logic
n 04

Total lines

2*rows - 1

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The inner loop runs k from 1 to 2*i-1. As i grows, the count becomes 1, 3, 5, 7, and so on.
Before printing digits, the program prints rows-i leading spaces. Smaller rows get more spaces, so the diamond stays centered.
After the top half (i=1..rows), a second outer loop runs i from rows-1 down to 1 with the same space and digit logic.
On row i=5, k runs while k < 2*i, so k goes 1..9 — nine concatenated digits.
Yes. Print k + " " inside the digit loop — see Example 3. You may need to adjust indentation.
O(n²) for n rows because total printed digits grow with the diamond width across both halves.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.
You get a single centered row with just the digit 1.

Did you Know? 🔊

Each row prints digits 1..(2*i-1) concatenated without spaces. Leading spaces center the shape; a second loop mirrors the top half downward.

Continue to Program 45

Move on to the star cross pattern with 0s in the Java number-pattern series.

Program 45 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful