Alternating Row Number Triangle (Zigzag)

What You’ll Learn
How to print a triangle where numbers continue increasing, but the direction flips on each row:
Odd rows: left-to-right (ascending). Even rows: right-to-left (descending).
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15Complete JavaScript Program
We track the next number k. For row i, the row range is k..k+i-1. Odd rows print ascending; even rows print descending.
const rows = 5;
let k = 1;
for (let i = 1; i <= rows; i++) {
const start = k;
const end = k + i - 1;
const row = [];
if (i % 2 === 1) {
for (let v = start; v <= end; v++) row.push(v);
} else {
for (let v = end; v >= start; v--) row.push(v);
}
console.log(row.join(" "));
k = end + 1;
}🧠 How It Works
Set rows and start counter
rows = 5 and k = 1 sets the triangle height and the first number.
Compute the row range
Row i uses values from start = k to end = k + i - 1.
Odd rows go forward
If i is odd, we print start..end so the row is ascending.
Even rows go backward
If i is even, we print end..start so the row is descending.
Zigzag triangle
After printing a row, we move k to the next unused number and repeat.
Variation — Browser (aligned cells) Version
In the browser, you can align columns using fixed-width inline-block cells:
<!DOCTYPE html>
<html>
<body>
<script>
var rows = 5;
var k = 1;
for (var i = 1; i <= rows; i++) {
var start = k;
var end = k + i - 1;
if (i % 2 === 1) {
for (var v = start; v <= end; v++)
document.write('<span style="display:inline-block;width:2.5em;text-align:right">' + v + '</span>');
} else {
for (var v2 = end; v2 >= start; v2--)
document.write('<span style="display:inline-block;width:2.5em;text-align:right">' + v2 + '</span>');
}
document.write("<br>");
k = end + 1;
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
rowsto print a larger triangle - Pad numbers (
padStart) for clean console alignment - Use a different rule (e.g., reverse every 3rd row) for new variants
- Replace numbers with letters to build alternating alphabet patterns
Avoid
- Resetting
kinside the loop (you’ll repeat numbers) - Forgetting to update
kafter each row - Using
document.writeoutside demos (prefer DOM APIs in apps)
Key Takeaways
Row i contains i numbers, taken from a consecutive range.
Odd rows print ascending; even rows print descending.
Compute row range using start = k and end = k + i - 1.
Update k to end + 1 to keep numbers continuous.
❓ Frequently Asked Questions
k = 0. The pattern stays the same shape, just shifted by one.rows = n, total printed values are n(n+1)/2.Explore More JavaScript Number Patterns!
Zigzag patterns are great practice for ranges and direction control. Next, try the same idea in a matrix.
This zigzag triangle is a small version of the “snake order” idea often used to traverse grids in programming problems.
12 people found this page helpful
