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, printf, a live preview, algorithm steps, worked PHP 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
printf("%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 PHP you use an outer loop with odd widths ($i = 1, 3, 5, …), a space loop for centering, and an inner loop that prints printf("%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 printf("%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 (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 | (int) trim(fgets(STDIN)); | Flexible console programs |
| Cube variant | printf("%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++) echo " "; |
| Print squares | printf("%4d", $m * $m); $m++; |
| End the row | echo PHP_EOL; |
| 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 PHP pattern series start here before pyramids and diamonds.
Outer/inner bound practice with an immediate visual check.
Combine loops with fgets(STDIN) 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 PHP programs — fixed row count, fgets(STDIN) 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.
<?php
$rows = 5;
$maxOdd = 2 * $rows - 1;
$m = 1;
for ($i = 1; $i <= $maxOdd; $i += 2) {
for ($j = $i; $j < $maxOdd; $j++) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
printf("%4d", $m * $m);
$m++;
}
echo PHP_EOL;
} 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 trim(fgets(STDIN)) (check is_numeric() in real apps).
<?php
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
echo "Invalid input." . PHP_EOL;
exit(1);
}
$rows = (int) $input;
$maxOdd = 2 * $rows - 1;
$m = 1;
for ($i = 1; $i <= $maxOdd; $i += 2) {
for ($j = $i; $j < $maxOdd; $j++) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
printf("%4d", $m * $m);
$m++;
}
echo PHP_EOL;
} Same nested-loop core as Example 1; only the source of $rows changes. Non-numeric input fails is_numeric() — validate before casting to int 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.
<?php
$rows = 3;
$maxOdd = 2 * $rows - 1;
$m = 1;
for ($i = 1; $i <= $maxOdd; $i += 2) {
for ($j = $i; $j < $maxOdd; $j++) {
echo " ";
}
for ($k = 1; $k <= $i; $k++) {
printf("%4d", $m * $m * $m);
$m++;
}
echo PHP_EOL;
} Same loop structure; only the print expression changes to $m * $m * $m for consecutive cubes.
Set $rows = 5; and use fgets(STDIN) when reading input. Set $maxOdd, $m, and loop variables $i, $j, $k.
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.
printf("%4d", $m * $m) in a $k = 1..$i loop; increment $m, then echo PHP_EOL.
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 echo vs echo PHP_EOL without complex math.
Example: put echo PHP_EOL 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 fgets(STDIN) 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 PHP 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/$k for loops — or rename to $row/$col.
fgets(STDIN)Avoid crashes when the user types letters instead of a number.
Only call echo PHP_EOL after the inner loop finishes the row.
Store $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 echo PHP_EOL 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 printf("%4d", $m * $m) or echo for values; echo PHP_EOL 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 echo PHP_EOL glues every digit onto one endless line.
→ Always end the row after the inner loop.
Letters or empty input leave $rows uninitialized.
→ Prefer fgets(STDIN) and re-prompt on failure.
Printing bare $m * $m without %4d breaks column alignment once values reach three digits.
→ Use printf("%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 fgets(STDIN) leaves $rows unset — call is_numeric($input) 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.printf("%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 echo PHP_EOL only after both inner loops finish.
$m * $m counter before codingprintf("%4d", $m * $m) and echo PHP_EOL after each row$rows ≥ 1 for interactive programsfgets(STDIN) return value before using $rowsecho PHP_EOL inside the inner digit loop$rows = 1 edge casePrint the pattern the beginner-friendly way.
Odd widths: 1, 3, 5…
DefinitionCenters each row
CodePrints $m * $m with %4d
n² 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 PHP number-pattern series.
12 people found this page helpful