Continuous Number Triangle in JavaScript

What You’ll Learn
How to print a continuous number triangle where values keep increasing across rows instead of restarting each row.
This pattern is a classic exercise in using a shared state variable across nested loops.
⭐ Pattern Output
For rows = 4, the pattern looks like this:
1
2 3
4 5 6
7 8 9 10Complete JavaScript Program
Outer loop controls row size. Inner loop prints values and increments a running counter.
const rows = 4;
let k = 1;
for (let i = 1; i <= rows; i++) {
let line = "";
for (let j = 1; j <= i; j++) {
line += k + (j < i ? " " : "");
k++;
}
console.log(line);
}🧠 How It Works
Initialize counter
let k = 1; keeps track of next number to print.
Outer loop sets row length
for (let i = 1; i <= rows; i++) creates rows of length 1, 2, 3, and 4.
Inner loop prints and increments
Each inner iteration appends k and then increments it, so numbering continues across rows.
Output each row
console.log(line); prints one completed row before moving on.
Continuous numbering triangle
A shared counter is the key difference from row-reset patterns.
Variation — Browser (document.write) Version
Print the same pattern directly in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
let k = 1;
for (let i = 1; i <= 4; i++) {
for (let j = 1; j <= i; j++) {
document.write(k++ + " ");
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase row count to grow sequence depth
- Align columns with padding for neat triangular display
- Start counter from a custom number (e.g., 100)
- Print the same logic in reverse row order
- Render to a DOM container instead of
document.write
Avoid
- Resetting the counter inside the outer loop unintentionally
- Mixing row and counter variables in wrong scope
- Skipping validation for invalid row values
- Using
document.writein modern production apps
Key Takeaways
The outer loop controls how many numbers each row has.
A single running counter keeps numbering continuous.
Inner loop prints and increments in one pass.
This is a base pattern for Floyd-like number triangles.
❓ Frequently Asked Questions
rows = 5 in both examples.document.write for browser rendering.Explore More JavaScript Number Patterns!
Master running-counter patterns to solve a wide range of progressive sequence problems.
Continuous number triangles are foundational for many matrix-filling and indexing algorithms.
12 people found this page helpful
