Shape Rule
m² per value
Row 1 prints 1, row 2 prints 4 9 16, row 3 prints five squares — each value is the next perfect square.

The square number pyramid prints 1, then 4 9 16, then 25 36 49 64 81, … — a natural step after Program 40’s alternating 1/0 pattern. This tutorial covers odd-length rows, indentation centering, a running counter m, padStart(4) formatting, a live preview, worked JavaScript examples, edge cases, and complexity.
m² per value
Row 1 prints 1, row 2 prints 4 9 16, row 3 prints five squares — each value is the next perfect square.
r = 1..rows
for (let r = 1; r <= rows; r++) — each row appends 2*r - 1 perfect squares.
Center rows
" ".repeat(4 * (rows - r)) indents narrow rows so the pyramid stays centered.
Running sequence
Increment m, then append String(m*m).padStart(4, " ") — squares progress 1, 4, 9, 16, 25, … continuously.
2–5 levels
Pick a level count and draw the square-number pyramid in the browser.
Complexity
Total square prints = n² for n rows; extra memory stays O(1).
A square number pyramid prints perfect squares in centered rows of odd length — 1, then 3, then 5 squares per row. With rows = 5, the output starts with 1, then 4 9 16, then 25 36 49 64 81, and continues.
In JavaScript the outer loop runs r = 1..rows, leading spaces center each row, and the inner loop appends String(m*m).padStart(4, " ") while incrementing m.
It combines nested loops with math and formatted output — a key step after Program 40’s alternating rows.
Each row prints 2r - 1 squares.
Leading spaces shift narrow rows right.
Program 40 alternates 1/0; Program 41 prints perfect squares.
Follow Program 40; continue to Program 42 (hollow square) next.
In short: outer r = 1..rows, indent spaces, inner append String(m*m).padStart(4, " "), increment m, then console.log(line).
Given a row count rows (e.g. 5), print a centered pyramid of perfect squares using a running counter m and fixed-width columns.
// rows = 5 (conceptual shape)
// 1
// 4 9 16
// 25 36 49 64 81
// ... | Item | Type | Description |
|---|---|---|
rows | number | Number of pyramid rows — outer loop runs r = 1..rows. |
r | number | Outer loop — row index; inner loop prints 2*r - 1 squares. |
m | number | Running counter — each printed value is m*m. |
m = 0
for r from 1 to rows:
print leading spaces
for _ from 1 to (2*r - 1):
m++
print m*m with fixed width
print newline | Approach | Idea | Best for |
|---|---|---|
| Nested loops + counter | 1, 4 9 16, … | Learning and interviews |
| User-input rows | parseInt(prompt(), 10) | Flexible console programs |
| Left-aligned variant | Skip leading spaces | Easier tracing on paper |
| Goal | Pattern |
|---|---|
| Walk rows | for (let r = 1; r <= rows; r++) |
| Center row | line = " ".repeat(4 * (rows - r)) |
| Append squares | m += 1; line += String(m*m).padStart(4, " ") |
| Squares per row | for (let k = 0; k < 2 * r - 1; k++) |
| End the row | console.log(line) |
| Wider columns | padStart(6, " ") when squares exceed 999 |
| Program 40 contrast | Alternating 1/0 with shrinking rows — not perfect squares |
Same square-number pyramid — different ways to control rows and alignment.
r = 1..rowsEach row prints 2r-1 squares
m += 1; m*mContinuous perfect squares
4 * (rows - r)Leading spaces per row
padStart(4)Keeps columns aligned
Reach for this pattern when teaching formatted output, centering, and running counters with nested loops.
Natural follow-up — perfect squares in a centered pyramid instead of alternating binary digits.
Outer/inner bound practice with an immediate visual check.
Combine loops with prompt() for a flexible row count.
Print cubes with m**3 or skip centering for a left-aligned pyramid — see Example 3.
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 level count between 2 and 5 and draw the square-number pyramid in the browser.
Three complete JavaScript programs — fixed rows, prompt() input, and a left-aligned variant. Click View Output to reveal sample console results, or Try it Yourself to run the code live.
Print five rows of the square-number pyramid with nested loops and formatted output.
rows = 5Hard-coded row count — ideal for first demos and screenshots.
const rows = 5;
let m = 0;
for (let r = 1; r <= rows; r++) {
let line = " ".repeat(4 * (rows - r));
for (let k = 0; k < 2 * r - 1; k++) {
m += 1;
line += String(m * m).padStart(4, " ");
}
console.log(line);
} When r = 1, one square prints — 1. When r = 2, three squares print — 4 9 16 (from m = 2, 3, 4). Leading spaces shift narrow rows right so the pyramid stays centered.
Read the row count with prompt() instead of hard-coding 5.
Read rows with prompt() and parseInt() (check with Number.isFinite in real apps).
const rowsInput = prompt("Enter number of rows:");
const rows = parseInt(rowsInput, 10);
let m = 0;
if (!Number.isFinite(rows) || rows < 1) {
console.log("Please enter a positive integer.");
} else {
for (let r = 1; r <= rows; r++) {
let line = " ".repeat(4 * (rows - r));
for (let k = 0; k < 2 * r - 1; k++) {
m += 1;
line += String(m * m).padStart(4, " ");
}
console.log(line);
}
} Same square-filling core as Example 1; only the source of rows changes from a literal to user input. Non-numeric input yields NaN with bare parseInt() — use Number.isFinite for safer labs.
Skip the leading-space prefix to draw squares flush left — easier to trace on paper.
Same squares and counter — no leading spaces.
const rows = 5;
let m = 0;
for (let r = 1; r <= rows; r++) {
let line = "";
for (let k = 0; k < 2 * r - 1; k++) {
m += 1;
line += String(m * m).padStart(4, " ");
}
console.log(line);
} Only the leading-space prefix is removed — m*m and padStart(4) formatting stay the same as Example 1. Rows grow wider to the right without centering.
No imports needed. Set rows = 5, m = 0, and loop variable r.
for (let r = 1; r <= rows; r++) — each row appends 2*r - 1 perfect squares.
line = " ".repeat(4 * (rows - r)) — indents narrow rows so the pyramid stays centered.
m += 1; line += String(m*m).padStart(4, " ") — fixed-width perfect squares in sequence.
console.log(line) ends the row after the inner loop finishes.
Total prints for 5 rows = 1+3+5+7+9 = 25 — O(n²) time, O(1) extra memory.
rows = 5Trace each outer-loop value of r, indent count, square count, m range, and row output.
r | Spaces | Squares | m range | Values |
|---|---|---|---|---|
1 | 16 | 1 | 1 | 1 |
2 | 12 | 3 | 2–4 | 4 9 16 |
3 | 8 | 5 | 5–9 | 25 36 49 64 81 |
4 | 4 | 7 | 10–16 | 100 121 144 … 256 |
5 | 0 | 9 | 17–25 | 289 324 … 625 |
Squares per row = 2*r - 1 — total prints = 1+3+5+7+9 = 25 = 5² for 5 rows.
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 padStart(4) to padStart(6) when squares exceed 999.
Foundation for inverted, pyramid, diamond, and hollow variants.
Example: continue to Program 42 for a hollow square of 1s.
Practice print vs row newline without complex math.
Example: put console.log(line) inside the inner loop by mistake.
Add spaces between digits once the two-loop structure works.
Example: use padStart(6, " ") for larger pyramids.
Triangular totals make O(n²) concrete for beginners.
Example: count printed squares for 5 rows — total is 25 (5²).
Pair the pattern with Number.isFinite 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 JavaScript 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: trace r, m, and indent count on paper for rows = 3 before coding the full demo.
Small habits that keep number-pattern code clean.
String(m*m).padStart(4, " ") keeps columns aligned — widen to padStart(6) when squares exceed 999.
Use Number.isFinite(rows) so bad input does not crash when converting rows.
Only call console.log(line) after the inner loop finishes the row.
Print leading spaces before the inner loop — keep the square-print logic inside the inner loop only.
Trace r = 1, 2, 3 and watch m grow before coding the full rows = 5 demo.
Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put console.log(line) inside the inner loop.
Mistakes that commonly break square-number pyramids.
Each square lands on its own line — you get a column, not a pyramid.
→ Use line += String(m*m).padStart(4, " ") for squares; console.log(line) only after the inner loop.
Appending bare m*m without padStart(4) makes columns drift as numbers get wider.
→ Always use String(m*m).padStart(4, " ") (or wider) for aligned columns.
m = 0 inside the outer loop restarts squares on every row instead of continuing the sequence.
→ Initialize m = 0 once before the outer loop.
Omitting console.log(line) glues every digit onto one endless line.
→ Always end the row after the inner loop.
parseInt(prompt())Letters or empty input yield NaN with bare parseInt().
→ Catch ValueError and re-prompt on failure.
Check these inputs before calling the solution done.
Output is just 1 on one centered line.
Outer loop never runs — print nothing or show a message.
rows < 0Treat as invalid; re-prompt instead of silent empty output.
Two rows: 1 then 4 9 16.
Bare parseInt(prompt()) yields NaN on bad input — use Number.isFinite first.
Each row prints 2*r - 1 squares — total work grows as n².
Try these variations to lock in the pattern.
m*m with m**3r = 1..rows. Inner loop: for (let k = 0; k < 2*r - 1; k++). Value: m*m with padStart(4) width." ".repeat(4 * (rows - r)) centers rows; console.log(line) advances to the next line.rows > 0 for interactive programs; rows = 1 should print a single 1.n rows = n² — the sum of the first n odd numbers.Quick Takeaway: outer loop r = 1..rows, indent spaces, inner for (let k = 0; k < 2*r - 1; k++) with String(m*m).padStart(4, " "), then console.log(line).
| Program | Time | Extra space |
|---|---|---|
| Nested loops (Examples 1–3) | O(n²) | O(1) |
| Smaller demo (Example 3) | O(n²) | O(1) |
The square number pyramid is a compact nested-loop lesson: a running counter m prints perfect squares while leading spaces keep rows centered. Master the fixed-rows version, then try user input and the left-aligned variant.
Practice the three examples above, then continue to Program 42 for the hollow square of 1s.
Each value is m² — keep String(m*m).padStart(4, " ") for aligned columns and console.log(line) for the row break.
for (let r = 1; r <= rows; r++) in the outer loopfor (let k = 0; k < 2 * r - 1; k++) appends odd counts per rowString(m*m).padStart(4, " ") for aligned columns and console.log(line) after each rowline = " ".repeat(4 * (rows - r)) before the inner loopNumber.isFinite(rows) after parseInt(prompt())console.log(line) inside the inner square loopm inside the outer loop (breaks the sequence)rows = 1 edge casePrint the pattern the beginner-friendly way.
Each value is m²
Definitionfor (let r = 1; r <= rows; r++)
Codefor (let k = 0; k < 2*r - 1; k++)
Code4 * (rows - r) spaces
AlignO(n²) time
AnalysisEach appended value is m² from a running counter m. Row widths are odd (1, 3, 5, 7, 9) — total appends for n rows = n².
Move on to the hollow square of 1s in the JavaScript number-pattern series.
12 people found this page helpful