Java Square Number Pyramid Pattern

Beginner
7 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A square number pyramid prints consecutive squares (1, 4, 9, 16, …) in a centered triangle with odd-width rows.

Remember
Rule: maxOdd = 2*rows-1; m = 1
      for i = 1, 3, 5, … maxOdd:
        print leading spaces, then i values of format("%4d", m*m)

           1
       4   9  16
  25  36  49  64  81     ← rows = 3

Unlike Program 40 (repeated 1/0 digits), here a shared counter m feeds squared values into a centered pyramid.

How to Solve It

Walk odd widths i = 1, 3, 5, …; indent with spaces, then print i squares via m++.

MethodIdeaBest for
Three loops + formatOdd width, space indent, format("%4d", m*m)Learning, interviews, exams
Cube variantSame shape; print m*m*m instead of m*mWhen you want cubes in the same pyramid

Pseudocode

Pseudocode
maxOdd = 2 * rows - 1
m = 1
for i from 1 to maxOdd step 2:
    for j from i to maxOdd - 1:
        print "  "
    for k from 1 to i:
        print m*m (width 4); m = m + 1
    print newline

Cheat sheet

GoalPattern
Odd widthsfor (int i = 1; i <= maxOdd; i += 2)
Leading spacesfor (int j = i; j < maxOdd; j++) print(" ")
Print squareSystem.out.format("%4d", m * m); m++;
End the rowSystem.out.println();
Values per rowi (odd: 1, 3, 5, …)

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.print / formatStays on the same lineSpaces and each squared value
System.out.printlnEnds the current lineAfter spaces and numbers finish

Print values without a newline, then end the row once.

Live Preview

Change the row count and the square pyramid updates instantly.

Whole numbers from 2 to 5 (keeps %4d readable). Tap a chip or type a value — the preview redraws as you go.

Live result rows = 4 · 16 values
               1
           4   9  16
      25  36  49  64  81
 100 121 144 169 196 225 256

Worked Walkthrough — rows = 3

Trace odd width i, the m values used, and the printed squares.

iCountm usedSquaresPrinted row
11111
332..44, 9, 164 9 16
555..925..8125 36 49 64 81

Total values = 1 + 3 + 5 = 9 = 3². In general, n rows print n² numbers.

Java Programs

Three complete programs: fixed rows = 5, Scanner input, and a cube pyramid. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded size — three nested loops and %4d formatting.

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

1. Odd widths. i steps 1, 3, 5, … up to 2*rows-1.

2. Indent. The space loop prints " " so shorter rows sit centered.

3. Squares. format("%4d", m*m) prints the next square; m++ continues the sequence.

When i = 1: one value 1. When i = 3: 4, 9, 16.

Example 2 — Rows Input

Read rows at runtime. Same three-loop core.

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();
        if (rows < 1) return;

        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

1. Prompt and guard. Read rows; exit early if it is less than 1.

2. Same core. Only the source of rows changes from a literal to user input.

3. Safer input tip. Prefer:

Safer input
if (!sc.hasNextInt()) {
    System.out.println("Enter a positive integer.");
    return;
}
int rows = sc.nextInt();
if (rows < 1) {
    System.out.println("Enter a positive integer.");
    return;
}

Example 3 — Cube Pyramid

Same centered shape — print m*m*m instead of m*m.

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

1. Same structure. Odd widths and space indent are unchanged.

2. Cubes. Only the printed expression becomes m * m * m.

3. Width tip. Use %5d or wider when cubes grow past three digits.

Edge Cases & Pitfalls

Check these before calling the solution done.

println inside

Column of numbers

If println is inside the number loop, each square lands on its own line. Use format for values; println only after the row.

Reset m

Restarted squares

Declaring m = 1 inside the outer loop restarts the sequence every row instead of continuing.

No spaces

Left-aligned triangle

Skipping the space loop keeps the odd-width shape but loses the centered pyramid look.

No %4d

Crowded columns

Plain print(m*m) makes multi-digit squares crowd earlier columns.

rows = 1

Single value

Output is just 1 on one line.

Bad input

Use hasNextInt

nextInt() throws on letters — prefer hasNextInt() and require a positive integer.

Time and Space Complexity

ProgramTimeExtra space
Square / cube pyramid (Examples 1–3)O(n²)O(1)

Total values = 1 + 3 + … + (2n−1) = n². Only loop counters are stored.

Key Takeaways

  • Rule: odd width i; print i values of m*m with %4d, then m++.
  • Keep m outside: one shared counter continues the square sequence across rows.
  • Center first: print leading " " spaces before the numbers on each row.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each odd width, indent with spaces, print i squares via format("%4d", m*m), then println().

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 n² for n rows.

Next: Hollow Square of 1s

Move on to the hollow square of ones 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