Centered Increasing Number Pyramid in JavaScript

What You’ll Learn
How to print a centered number pyramid where numbers increase continuously across rows: 1, then 2 3, then 4 5 6, and so on.
You’ll learn how to keep alignment stable by printing empty cells first and using a single counter variable.
⭐ Pattern Output
For size = 5, the pattern looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15Complete JavaScript Program
We print a fixed number of โcellsโ per row. If we’re before the row start (j > i), we print an empty cell; otherwise we print the next number.
const size = 5;
let k = 1;
for (let i = 1; i <= size; i++) {
let line = "";
for (let j = size; j >= 1; j--) {
if (j > i) {
line += " ";
} else {
line += String(k++).padStart(2, " ") + " ";
}
}
console.log(line.trimEnd());
}🧠 How It Works
Initialize the counter
let k = 1; is the next value to print, and it keeps increasing across rows.
Outer loop controls rows
i runs from 1..size, so each row prints one more number than the previous row.
Inner loop creates fixed-width cells
The loop j = size..1 ensures each row has the same number of cell positions, which makes centering easy.
Decide empty vs filled cell
If j > i, we add empty spacing; otherwise we print k and increment it.
Centered pyramid
Empty cells on the left push the printed numbers to the center.
Variation — Browser (fixed-width <div> cells)
In the browser, using fixed-width inline blocks keeps multi-digit numbers aligned:
<!DOCTYPE html>
<html>
<head>
<style>
.cell {
display: inline-block;
width: 28px;
text-align: center;
}
</style>
</head>
<body>
<script>
var i, j, k = 1;
for (i = 1; i <= 5; i++) {
for (j = 5; j >= 1; j--) {
if (j > i)
document.write("<span class='cell'></span>");
else
document.write("<span class='cell'>" + (k++) + "</span>");
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
sizeto print more rows (numbers will continue beyond 15) - Pad numbers (e.g.,
padStart(3)) for larger sizes - Restart numbering each row by resetting
kinside the outer loop - Center-align using DOM instead of
document.writein real projects
Avoid
- Using variable-width spacing when numbers reach 2+ digits (alignment breaks)
- Forgetting line breaks after each row
- Relying on
document.writefor production code
Key Takeaways
A single counter k creates a continuous sequence across rows.
Printing empty cells first helps center-align the pyramid.
Fixed-width formatting is essential once values become multi-digit.
Total numbers printed are 1+2+…+n = n(n+1)/2.
❓ Frequently Asked Questions
k to your start value, for example let k = 10;.padStart) and print consistent empty-cell spacing before the numbers.Explore More JavaScript Number Patterns!
Try mixing centering + counters to build Floyd triangles and number pyramids.
Floyd-style patterns use one counter across rows. That means the last number is the triangular number n(n+1)/2 for n rows.
12 people found this page helpful
