Square Number Pyramid Pattern in Java

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

What You’ll Learn

The square number pyramid prints consecutive squares in a centered triangle with odd-width rows. This tutorial covers the three-loop row structure, System.out.format, a live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Odd widths, centered

Row widths are 1, 3, 5, … up to 2*rows-1; each value is m*m.

Space Loop

Center rows

for (j = i; j < maxOdd; j++) prints leading space pairs before each row.

Number Loop

m*m squares

System.out.format("%4d", m*m) prints i squares per row; m increments each time.

Outer Loop

i += 2

for (i = 1; i <= maxOdd; i += 2) walks odd row widths only.

Live Preview

1–20 rows

Pick a row count and draw the square number pyramid instantly in the browser.

O(n²)

Complexity

Total numbers = ; extra memory stays O(1).

Introduction

A square number pyramid prints consecutive squares in a centered triangle. With rows = 5, the output starts with 1, then 4 9 16, building to a widest row of nine squared values.

In Java you use an outer loop with odd widths (i = 1, 3, 5, …), a space loop for centering, and an inner loop that prints System.out.format("%4d", m*m) while incrementing m.

Why it matters?

It teaches three nested loops on one row plus formatted output — a key step before hollow pyramids and diamonds.

Key Highlights

Odd Row Widths

Outer loop uses i = 1, 3, 5, … up to 2*rows-1.

Centered Rows

Leading space pairs shift smaller rows to the right.

Squared Values

Counter m prints m*m with %4d formatting.

Series Foundation

Follow Program 40 alternating 1/0; continue to Program 42 hollow square.

In short: for each odd width i up to 2*rows-1, print leading spaces, then print i squared values with System.out.format("%4d", m*m), incrementing m each time.

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print a centered pyramid of consecutive squares. Row widths are odd: 1, 3, 5, … up to 2*rows-1.

Java
// rows = 3 (conceptual shape — columns aligned with %4d)
//         1
//     4   9  16
// 25  36  49  64  81

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextCentered rows of squared integers; row width i prints i values.

Minimal workflow

Pseudocode
for i from 1 to 2*rows-1 step 2:
    print leading spaces (i .. maxOdd-1)
    repeat i times:
        print m*m with fixed width; m++
    print newline

Approach comparison

ApproachIdeaBest for
Three nested loops1, then 4 9 16, …Learning and interviews
User-input rowssc.nextInt();Flexible console programs
Cube variantSystem.out.format("%4d", m*m*m)Extending the same structure

⚡ Quick Reference

GoalPattern
Odd-width rowsfor (i = 1; i <= maxOdd; i += 2)
Center with spacesfor (j = i; j < maxOdd; j++) System.out.print(" ");
Print squaresSystem.out.format("%4d", m*m); m++;
End the rowSystem.out.println();
Program 40 contrastAlternating 1/0 uses parity; this pyramid uses odd widths + formatting

📋 Spaces vs Squares vs Combined

Same pyramid row — how the space loop and number loop work together.

Space loop
j = i..maxOdd-1

Leading pairs of spaces center each row

Number loop
k = 1..i

Prints m*m with %4d; increments m

Row width
odd i

Widths 1, 3, 5, … keep the pyramid symmetric

Learning tip
trace i=3

Dry-run row 3: spaces then three squares 4, 9, 16

Context

When This Pattern Shows Up

Reach for this pattern when teaching space alignment and one inner loop on the same row.

  1. First lab exercise

    Most Java pattern series start here before pyramids and diamonds.

  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 40 (alternating 1/0), then continue to Program 42 (hollow square).

  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 square number pyramid 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-output variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with three nested loops per line.

Example 1 — Fixed rows = 5

Hard-coded size — three nested loops build each centered row of squares.

Java
public class SquareNumberPyramid {
    public static void main(String[] args) {
        int rows = 5;
        int maxOdd = 2 * rows - 1;

        int m = 1;
        for (int i = 1; i <= maxOdd; i += 2) {
            for (int j = i; j < maxOdd; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%4d", m * m);
                m++;
            }
            System.out.println();
        }
    }
}

How It Works

When i = 1, the space loop indents the row and one square 1 prints. When i = 3, three values appear: 4, 9, 16 — with m at 2, 3, 4.

📈 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 SquareNumberPyramidInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();
        int maxOdd = 2 * rows - 1;

        int m = 1;
        for (int i = 1; i <= maxOdd; i += 2) {
            for (int j = i; j < maxOdd; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%4d", m * m);
                m++;
            }
            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

Same pyramid structure printing cubes instead of squares.

Example 3 — Cube Pyramid

Replace m*m with m*m*m to print consecutive cubes in the same centered shape.

Java
public class SquareNumberPyramidCubes {
    public static void main(String[] args) {
        int rows = 3;
        int maxOdd = 2 * rows - 1;

        int m = 1;
        for (int i = 1; i <= maxOdd; i += 2) {
            for (int j = i; j < maxOdd; j++) {
                System.out.print("  ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.format("%4d", m * m * m);
                m++;
            }
            System.out.println();
        }
    }
}

How It Works

Same loop structure; only the print expression changes to m*m*m for consecutive cubes.

🧠 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 (odd widths)

for (i = 1; i <= maxOdd; i += 2) — row widths 1, 3, 5, … up to 2*rows-1.

Row
3

Space loop (center)

for (j = i; j < maxOdd; j++) prints leading space pairs before the numbers.

Width
4

Number loop (squares)

System.out.format("%4d", m*m) in a k = 1..i loop; increment m, then println().

Squares
=

Square number pyramid complete

Total number prints: O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 3

Trace each odd width: leading spaces, values printed, and running counter m.

i (width)Spaces (j)m rangeSquares printed
14 pairs11
32 pairs2–44 9 16
50 pairs5–925 36 49 64 81

Total number prints: 1+3+5 = 9 = = .

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: change j <= i and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: change k start to 100 for a shifted sequence.

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: use %4d when values exceed two digits.

5. Complexity Intuition

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

Example: count printed digits for n = 10 still → 55.

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 bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the three-loop row version first; then try the cube 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

    Store int sq = m * m; once per inner iteration when debugging row traces.

  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 single digits per line, you almost certainly put System.out.println() inside the inner loop.

Common Pitfalls

Mistakes that commonly break square number pyramids.

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

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

    → Use System.out.print for the digit; System.out.println() only after the inner loop.

  2. 2. Wrong Space Loop

    Using j = 1..i for spaces pushes rows left instead of centering them.

    → Keep for (j = i; j < maxOdd; j++) to print the correct leading indent.

  3. 3. Forgetting the Row Break

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

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw undefined rows.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Unformatted Numbers

    Printing bare m*m without %4d breaks column alignment once values reach three digits.

    → Use System.out.format("%4d", m*m) or widen the field for larger pyramids.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit

Output is just 1 on one 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 n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric Scanner input

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

Fill char

Cube variant

Swap m*m for m*m*m — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Alternating 1/0 pattern

  • Parity check with shrinking width
  • Review Program 40

2. Hollow square of 1s

  • Border-only square with nested loops
  • Continue with Program 42

3. Cube pyramid

  • Replace m*m with m*m*m
  • Same three-loop structure

4. Wider formatting

  • Use %5d when squares exceed 999
  • Keep columns aligned for large rows

Notes

  • Square count. Total prints for n rows is — odd widths sum to a perfect square.
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Use System.out.format("%4d", m*m) so columns stay aligned as values grow.

Quick Takeaway: odd-width outer loop, space loop for centering, number loop for m*m, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Cube variant (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The square number pyramid combines an odd-width outer loop with a space loop and a number loop — a natural step after alternating 1/0 patterns. Master the fixed-rows version first, then try user input and the cube variant.

Practice the three examples above, then continue to Program 42 for the hollow square of 1s.

Row width i prints i squares — keep println() only after both inner loops finish.

💡 Best Practices

✅ Do

  • Explain odd widths, space loop, and m*m counter before coding
  • Use System.out.format("%4d", m*m) 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 space loop (pyramid aligns left)
  • Print unformatted squares when alignment matters
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this square number pyramid

Print the pattern the beginner-friendly way.

5
Core concepts
02

Space loop

Centers each row

Code
03

Number loop

Prints m*m with %4d

Logic
n 04

Total prints

n² numbers

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Odd widths (1, 3, 5, …) keep the pyramid symmetric. The last row has 2*rows-1 numbers.
A counter m starts at 1 and increments after every print. The program outputs m*m, producing 1, 4, 9, 16, 25, and so on.
Before printing numbers, a space loop runs from j=i to maxOdd-1, printing leading pairs of spaces so smaller rows shift right.
Fixed-width columns keep alignment when values grow to three digits (121) or more.
Yes. Replace m*m with m*m*m — see Example 3.
O(n²) for n rows because total printed numbers are 1+3+5+…+(2n-1) = n².
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.
maxOdd becomes negative or zero and the outer loop never runs. Validate and prompt again for interactive programs.

Did you Know? 🔊

Each row prints an odd count of squared values (1, 3, 5, …). A counter m increments after every print and the program outputs m*m with fixed-width formatting — total numbers equal for n rows.

Continue to Program 42

Move on to the hollow square of 1s in the Java number-pattern series.

Program 42 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