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

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.
Odd widths, centered
Row widths are 1, 3, 5, … up to 2*rows-1; each value is m*m.
Center rows
for (j = i; j < maxOdd; j++) prints leading space pairs before each row.
m*m squares
System.out.format("%4d", m*m) prints i squares per row; m increments each time.
i += 2
for (i = 1; i <= maxOdd; i += 2) walks odd row widths only.
1–20 rows
Pick a row count and draw the square number pyramid instantly in the browser.
Complexity
Total numbers = n²; extra memory stays O(1).
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.
It teaches three nested loops on one row plus formatted output — a key step before hollow pyramids and diamonds.
Outer loop uses i = 1, 3, 5, … up to 2*rows-1.
Leading space pairs shift smaller rows to the right.
Counter m prints m*m with %4d formatting.
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.
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.
// rows = 3 (conceptual shape — columns aligned with %4d)
// 1
// 4 9 16
// 25 36 49 64 81 | Item | Type | Description |
|---|---|---|
rows | int | Number of triangle lines to print (typically ≥ 1). |
| Printed output | text | Centered rows of squared integers; row width i prints i values. |
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 | Idea | Best for |
|---|---|---|
| Three nested loops | 1, then 4 9 16, … | Learning and interviews |
| User-input rows | sc.nextInt(); | Flexible console programs |
| Cube variant | System.out.format("%4d", m*m*m) | Extending the same structure |
| Goal | Pattern |
|---|---|
| Odd-width rows | for (i = 1; i <= maxOdd; i += 2) |
| Center with spaces | for (j = i; j < maxOdd; j++) System.out.print(" "); |
| Print squares | System.out.format("%4d", m*m); m++; |
| End the row | System.out.println(); |
| Program 40 contrast | Alternating 1/0 uses parity; this pyramid uses odd widths + formatting |
Same pyramid row — how the space loop and number loop work together.
j = i..maxOdd-1Leading pairs of spaces center each row
k = 1..iPrints m*m with %4d; increments m
odd iWidths 1, 3, 5, … keep the pyramid symmetric
trace i=3Dry-run row 3: spaces then three squares 4, 9, 16
Reach for this pattern when teaching space alignment and one inner loop on the same row.
Most Java pattern series start here before pyramids and diamonds.
Outer/inner bound practice with an immediate visual check.
Combine loops with Scanner for a flexible row count.
Compare with Program 40 (alternating 1/0), then continue to Program 42 (hollow square).
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.
Choose a row count between 1 and 20 and draw the square number pyramid in the browser.
Three complete Java programs — fixed row count, Scanner input, and a spaced-output variant. Click View Output to reveal sample console results.
Print five rows with three nested loops per line.
rows = 5Hard-coded size — three nested loops build each centered row of squares.
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();
}
}
} 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.
Let the user choose the height at runtime.
Read the row count with Scanner.nextInt() (check hasNextInt() in real apps).
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();
}
} 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.
Same pyramid structure printing cubes instead of squares.
Replace m*m with m*m*m to print consecutive cubes in the same centered shape.
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();
}
}
} Same loop structure; only the print expression changes to m*m*m for consecutive cubes.
System.out is built in; use Scanner when reading input. Set rows (fixed or from input).
for (i = 1; i <= maxOdd; i += 2) — row widths 1, 3, 5, … up to 2*rows-1.
for (j = i; j < maxOdd; j++) prints leading space pairs before the numbers.
System.out.format("%4d", m*m) in a k = 1..i loop; increment m, then println().
Total number prints: n² — O(n²) time, O(1) extra memory.
rows = 3Trace each odd width: leading spaces, values printed, and running counter m.
i (width) | Spaces (j) | m range | Squares printed |
|---|---|---|---|
1 | 4 pairs | 1 | 1 |
3 | 2 pairs | 2–4 | 4 9 16 |
5 | 0 pairs | 5–9 | 25 36 49 64 81 |
Total number prints: 1+3+5 = 9 = 3² = n².
Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.
Clearest visual proof that outer and inner bounds interact.
Example: change j <= i and watch the shape change.
Foundation for inverted, pyramid, diamond, and hollow variants.
Example: change k start to 100 for a shifted sequence.
Practice System.out.print vs row newline without complex math.
Example: put System.out.println() inside the inner loop by mistake.
Swap digits for letters, stars, or spaced output once the loop works.
Example: use %4d when values exceed two digits.
Triangular totals make O(n²) concrete for beginners.
Example: count printed digits for n = 10 still → 55.
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.
Why this pattern earns a permanent spot in beginner Java courses.
Wrong bounds show up immediately as a broken staircase.
Only loops and console output — no arrays or math libraries.
Invert, center, hollow, or change the fill character with small edits.
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.
Small habits that keep number-pattern code clean.
Use rows (or n) and keep i/j for row/column — or rename to row/col.
ScannerAvoid crashes when the user types letters instead of a number.
Only call System.out.println() after the inner loop finishes the row.
Store int sq = m * m; once per inner iteration when debugging row traces.
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.
Mistakes that commonly break square number pyramids.
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.
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.
Omitting System.out.println() glues every digit onto one endless line.
→ Always end the row after the inner loop.
Letters or empty input throw undefined rows.
→ Prefer Scanner and re-prompt on failure.
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.
Check these inputs before calling the solution done.
Output is just 1 on one line.
Outer loop never runs — print nothing or show a message.
rows < 0Treat as invalid; re-prompt instead of silent empty output.
Output grows as n²/2 characters — fine for labs, noisy for huge n.
Unchecked Scanner leaves rows unset — call sc.hasNextInt() first.
Swap m*m for m*m*m — see Example 3.
Try these variations to lock in the pattern.
m*m with m*m*m%5d when squares exceed 999n² — odd widths sum to a perfect square.print stays on the line; println advances — mix them carefully.rows > 0 for interactive programs; rows = 1 should print a single 1.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.
| Program | Time | Extra space |
|---|---|---|
| Nested loops (Examples 1–2) | O(rows²) | O(1) |
| Cube variant (Example 3) | O(rows²) | O(1) |
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.
m*m counter before codingSystem.out.format("%4d", m*m) and println() after each rowrows ≥ 1 for interactive programsScanner return value before using rowsSystem.out.println() inside the inner digit looprows = 1 edge casePrint the pattern the beginner-friendly way.
Odd widths: 1, 3, 5…
DefinitionCenters each row
CodePrints m*m with %4d
Logicn² numbers
I/OO(n²) time
AnalysisEach 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.
Move on to the hollow square of 1s in the Java number-pattern series.
12 people found this page helpful