Staggered Number Triangle in JavaScript

What You’ll Learn
How to print a staggered number triangle where each row begins with i, then appends additional values computed using a decrementing offset.
This is a great exercise for understanding how multiple variables (k and m) can interact across nested loops.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15Complete JavaScript Program
Outer loop starts each row with i. Inner loop prints computed k values while m decreases.
const rows = 5;
for (let i = 1; i <= rows; i++) {
// Offset starts high and decreases each time we append a value.
let m = rows - 1;
let k = i + m;
let line = "" + i;
for (let j = 1; j < i; j++) {
line += " " + k;
m--;
k = k + m;
}
console.log(line);
}🧠 How It Works
Setup m and k
For each row, m = rows - 1 and k = i + m prepare the next computed value.
Outer loop builds rows
for (let i = 1; i <= rows; i++) chooses how many rows to print.
Start line with i
The code sets line = "" + i, so every row begins with the row index.
Inner loop appends computed values
Each pass appends k, then updates it with a decreasing m (using m-- and k = k + m).
Final staggered triangle
The combination of row start + decrementing offset creates the pattern.
Variation — Browser (document.write) Version
Print the same triangle directly in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
for (let i = 1; i <= 5; i++) {
document.write(i + " ");
let m = 4;
let k = i + m;
for (let j = 1; j < i; j++) {
document.write(k + " ");
m--;
k = k + m;
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
rowsto print a larger triangle - Adjust the initial offset to experiment with similar patterns
- Use an array and
join(' ')for cleaner spacing - Render output into the DOM instead of using
document.write
Avoid
- Using the wrong loop condition (off-by-one in
j < i) - Updating
kbefore decrementingm - Mixing
mandkupdates in the wrong scope - Resetting variables inside the inner loop unless required
Key Takeaways
The outer loop controls how many rows are printed.
Each row begins with i, which anchors the triangle.
A decrementing m updates k to generate staggered values.
This pattern demonstrates how to combine multiple variables across loops.
❓ Frequently Asked Questions
m = rows - 1 (so m = 4 when rows = 5) and computes k = i + m → k = 2 + 4 = 6.rows to 6 and keep the offset as m = rows - 1 so the computed k values stay consistent.textContent (recommended for real apps).n(n+1)/2 numbers.Explore More JavaScript Number Patterns!
Master staggered-offset patterns to solve a wide range of progressive sequence problems.
Staggered triangles are a common stepping stone toward matrix-filling and indexing patterns in programming.
12 people found this page helpful
