0-Based Increasing Sum Triangle in JavaScript

What You’ll Learn
How to print a triangle where each value is simply the sum of the row and column indices: i + j.
This is a clean introduction to 0-based loops and pattern printing in JavaScript.
⭐ Pattern Output
For maxRow = 5, the pattern looks like this:
0
1 2
2 3 4
3 4 5 6
4 5 6 7 8
5 6 7 8 9 10Complete JavaScript Program
The outer loop starts at 0. For each row i, the inner loop prints j from 0 to i and outputs i + j.
const maxRow = 5;
for (let i = 0; i <= maxRow; i++) {
let line = "";
for (let j = 0; j <= i; j++) {
line += (i + j) + (j === i ? "" : " ");
}
console.log(line);
}🧠 How It Works
Choose the maximum row
maxRow = 5 means we print rows from 0 to 5 (6 rows total).
Outer loop controls row index i
i starts at 0, so the first line contains a single value.
Inner loop runs from 0..i
That makes row i print i + 1 numbers.
Print i + j
The expression i + j increases by 1 as j increases across the row.
Row is a shifted range
Row 4 starts at 4 and ends at 8 because it prints 4+0 through 4+4.
Variation — Browser (document.write) Version
Print the triangle in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 0; i <= 5; i++) {
for (j = 0; j <= i; j++)
document.write(i + j + " ");
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change the start index to 1 to match 1-based triangles
- Add an offset: print
(base + i + j)to shift all values - Pad numbers for alignment when values become two digits
- Reverse the triangle by looping i downward
Avoid
- Mixing 0-based and 1-based bounds (causes off-by-one issues)
- Printing without separators (multi-digit numbers can merge)
- Forgetting line breaks in browser output
Key Takeaways
Using 0-based loops changes the first row output to 0.
Row i prints values from i up to 2i using i + j.
Inner loop bound j <= i controls the triangle growth.
This pattern is a foundation for many arithmetic-based triangles.
❓ Frequently Asked Questions
j = 5, so the last value is 5 + 5 = 10.i + j - 1.i + j lie on the same diagonal, which is why sum-based patterns look “shifted”.Explore More JavaScript Number Patterns!
Try changing formulas to see how patterns transform with small math tweaks.
Printing i + j is one of the simplest ways to generate arithmetic patterns—yet it connects to diagonals, sums, and even dynamic programming tables.
12 people found this page helpful
