Sequential Decreasing-Width Number Triangle in JavaScript

What You’ll Learn
How to print consecutive numbers in a triangle where each next row prints one fewer number.
This is a simple and useful practice exercise for nested loops and formatting.
⭐ Pattern Output
For rows = 5, the output looks like this:
1 2 3 4 5\n6 7 8 9\n10 11 12\n13 14\n15Complete JavaScript Program
The inner loop prints fewer values each row, while k keeps increasing.
const rows = 5;
let k = 1;
for (let i = 1; i <= rows; i++) {
const row = [];
for (let j = rows; j >= i; j--) {
row.push(k++);
}
console.log(row.join(" "));
}🧠 How It Works
Initialize rows and counter
rows controls the triangle height, and k starts at 1.
Outer loop for each row
i goes from 1 to rows, producing one output line per iteration.
Inner loop decreases the width
The inner loop runs from rows down to i, so each row prints one fewer number than the previous row.
Increment k each time
k++ ensures the numbers remain sequential across all rows.
Sequential triangle
Total prints are \(rows(rows+1)/2\), so runtime grows like O(n²).
Variation — Browser Grid Version
Print the same pattern in the browser using fixed-width cells for clean alignment:
<!DOCTYPE html>
<html>
<head>
<style>
.cell { display:inline-block; width:2.2em; text-align:right; }
</style>
</head>
<body>
<script>
var rows = 5;
var k = 1;
for (var i = 1; i <= rows; i++) {
for (var j = rows; j >= i; j--) {
document.write('<span class="cell">' + (k++) + '</span>');
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
rowsto print bigger triangles - Start from a different number by changing the initial value of
k - Use
padStartto align larger numbers - Build each row as a string and then print once for cleaner output formatting
Avoid
- Hard-coding the number 5 in multiple places (use
rows) - Forgetting the line break at the end of each row
- Using
document.writein production (fine for demos)
Key Takeaways
A decreasing-width triangle can be done by changing the inner loop bounds.
A single counter (k) keeps the sequence continuous across rows.
Total printed values are \(rows(rows+1)/2\).
Use fixed-width formatting (pads/spans) to keep the output neat.
❓ Frequently Asked Questions
k++ with the inner-loop variable (like j or another counter).i = rows, the inner loop runs only once, so it prints one value.rows - i, and adjust spacing between numbers accordingly.Explore More JavaScript Number Patterns!
Try combining sequential counters with different triangle shapes.
The total numbers printed in this triangle is the triangular number \(rows(rows+1)/2\).
12 people found this page helpful
