Alternating 1 and 0 Pattern (Decreasing Length) in JavaScript

What You’ll Learn
How to print an alternating pattern where odd rows contain only 1 and even rows contain only 0.
Each next row is shorter than the previous one, giving the triangle-like output.
⭐ Pattern Output
For size = 5, the pattern looks like this:
11111
0000
111
00
1Complete JavaScript Program
The inner loop prints size - i + 1 characters. The printed character is 0 when i is even; otherwise it’s 1.
const size = 5;
for (let i = 1; i <= size; i++) {
let line = "";
const ch = (i % 2 === 0) ? "0" : "1";
for (let j = i; j <= size; j++) {
line += ch;
}
console.log(line);
}🧠 How It Works
Set the size
size = 5 sets both the number of rows and the first row length.
Outer loop controls rows
Row i will print size - i + 1 digits.
Pick 0 or 1 by parity
If i is even, print 0; otherwise print 1.
Inner loop prints remaining length
for (j = i; j <= size; j++) runs fewer times each row, shrinking the output.
Even row prints zeros
Row 2 is even, so it prints 0 four times.
Variation — Browser (document.write) Version
Print the same pattern in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
var i, j;
for (i = 1; i <= 5; i++) {
for (j = i; j <= 5; j++) {
if (i % 2 == 0)
document.write("0");
else
document.write("1");
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change size to create a bigger triangle
- Swap the digits so odd rows print 0 and even rows print 1
- Print spaces between digits for readability
- Make a checkerboard by alternating inside the inner loop too
Avoid
- Forgetting that the inner loop controls the row length
- Mixing string and numeric output unintentionally
- Hard-coding values if you want reuse (prefer variables)
Key Takeaways
Row parity (even/odd) can control which digit is printed.
Decreasing row length is created by starting the inner loop at i.
This is a simple example of using conditions inside loops.
Small variations produce many new patterns.
❓ Frequently Asked Questions
(j % 2) inside the inner loop to switch between 0 and 1 by column position.Explore More JavaScript Number Patterns!
Even/odd logic is a powerful tool for alternating patterns and checkerboards.
Parity checks (even vs odd) are one of the simplest ways to create alternating patterns. You can alternate by row, by column, or by the sum i + j.
12 people found this page helpful
