Alternating 1 and 0 Triangle in JavaScript

Beginner
⏱️ 7 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo + Nested Loops

What You’ll Learn

The alternating 1 and 0 triangle prints 11111, 0000, 111, 00, 1 — a natural step after the rotating number pattern in Program 39. This tutorial covers modulo parity, shrinking inner-loop width, nested loops, a live preview, algorithm steps, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Parity + shrinking width

Row 1 prints 11111, row 2 prints 0000, shrinking until a single 1 — odd rows are 1s, even rows are 0s.

Outer Loop

1..rows

for (let i = 1; i <= rows; i++) walks each row and supplies the parity value via i % 2.

Inner Loop

i..rows ascending

for (let j = i; j <= rows; j++) repeats the row digit rows - i + 1 times.

Modulo parity

i % 2

line += i % 2 appends 1 on odd rows and 0 on even rows.

Live Preview

3–9 rows

Pick a row count and draw the alternating 1/0 triangle in the browser.

O(n²)

Complexity

Total digit prints = n(n+1)/2; extra memory stays O(1).

Introduction

An alternating 1 and 0 triangle prints odd rows filled with 1s and even rows filled with 0s, while each row gets shorter. With rows = 5, the output is 11111, 0000, 111, 00, 1.

In JavaScript the outer loop runs i = 1..rows, the inner loop repeats i % 2 via for (let j = i; j <= rows; j++), then console.log(line) moves to the next line.

Why it matters?

It teaches modulo parity and shrinking inner-loop bounds — a key step after Program 39’s rotating rows.

Key Highlights

Parity rule

i % 2 picks 1 or 0 for the whole row.

Shrinking width

Inner loop starts at i and runs to rows.

vs Program 39

Program 39 rotates digits; Program 40 alternates binary digits by row parity.

Series Foundation

Follow Program 39; continue to Program 41 (square numbers pyramid) next.

In short: for each i from 1 to rows, append i % 2 repeatedly for j = i..rows, then console.log(line).

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print an alternating 1/0 triangle: odd rows are all 1s, even rows are all 0s, with each row one character shorter.

JavaScript
// rows = 5 (conceptual shape)
// 11111
// 0000
// 111
// 00
// 1

Inputs & Outputs

ItemTypeDescription
rowsnumberNumber of triangle lines and width of the first row.
inumberOuter loop — row index from 1 to rows; also supplies parity via i % 2.
_Inner loop — repeats the row digit rows - i + 1 times via for (let j = i; j <= rows; j++).

Minimal workflow

Pseudocode
for i from 1 to rows:
    digit = i % 2
    for _ from i to rows:
        print digit
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + modulo11111, 0000, …Learning and interviews
User-input rowsparseInt(prompt(), 10)Flexible console programs
Spaced outputline += (i % 2) + " "Easier reading per row

⚡ Quick Reference

GoalPattern
Walk rowsfor (let i = 1; i <= rows; i++)
Append parity digitline += i % 2
Repeat per rowfor (let j = i; j <= rows; j++)
End the rowconsole.log(line)
Spaced digitsline += (i % 2) + " "
Flip 1s and 0sline += 1 - (i % 2)
Program 39 contrastRotating digits i..rows then wrap — not binary parity

📋 Fixed Rows vs User Input vs Spaced Output

Same alternating 1/0 triangle — different ways to control rows and formatting.

Outer loop
i = 1..rows

Supplies parity via i % 2

Inner loop
_ = i..rows

Shrinking row width each line

First row
i = 1

Longest row of 1s on top

Learning tip
i % 2

Odd → 1, even → 0

Context

When This Pattern Shows Up

Reach for this pattern when teaching modulo parity and shrinking inner-loop bounds.

  1. After Program 39

    Natural follow-up — alternating binary digits by row parity instead of rotating numbers.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with prompt() for a flexible row count.

  4. Gateway to variants

    Flip parity with 1 - (i % 2) or try per-column alternation with (i + j) % 2.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 9 and draw the alternating 1/0 triangle in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed rows, prompt() input, and spaced output variant. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print five rows of the alternating 1/0 triangle with nested loops and modulo.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = i; j <= rows; j++) {
    line += i % 2;
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 1 (odd), the inner loop prints 1 five times — output 11111. When i = 2 (even), it prints 0 four times — output 0000. The outer loop increases i each row, shortening the inner loop.

📈 User Input

Read the row count with prompt() instead of hard-coding 5.

Example 2 — User Input

Read rows with prompt() and parseInt() (check with Number.isFinite in real apps).

JavaScript
const rowsInput = prompt("Enter the number of rows:");
const rows = parseInt(rowsInput, 10);

if (!Number.isFinite(rows) || rows < 1) {
  console.log("Please enter a positive integer.");
} else {
  for (let i = 1; i <= rows; i++) {
    let line = "";
    for (let j = i; j <= rows; j++) {
      line += i % 2;
    }
    console.log(line);
  }
}
Try it Yourself

How It Works

Same modulo inner-loop core as Example 1; only the source of rows changes from a literal to user input. Non-numeric input yields NaN with bare parseInt() — use Number.isFinite for safer labs.

⚡ Spaced Output

Add a space between digits for easier reading on each row.

Example 3 — Spaced Characters

Keep rows = 5 but print each character followed by a space.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let line = "";
  for (let j = i; j <= rows; j++) {
    line += (i % 2) + " ";
  }
  console.log(line);
}
Try it Yourself

How It Works

Only the append changes — line += (i % 2) + " " instead of line += i % 2. Loop bounds and parity check stay the same as Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed for fixed rows; use prompt() when reading. Set rows = 5 and loop variable i.

Setup
2

Outer loop walks rows

for (let i = 1; i <= rows; i++) — ascending outer loop supplies parity via i % 2.

Row
3

Inner loop (repeat)

for (let j = i; j <= rows; j++) — repeats the row digit rows - i + 1 times.

Repeat
4

Parity check

line += i % 2 appends 1 for odd rows and 0 for even rows.

Modulo
5

New line

console.log(line) ends the row after the inner loop finishes.

Break
=

Alternating 1/0 triangle complete

Rows shrink from rows characters to one — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, the inner-loop range, character count, parity, and full row output.

iInner loopCharPrintsRow output
11, 2, 3, 4, 51511111
22, 3, 4, 5040000
33, 4, 513111
44, 50200
55111

Prints per row = rows - i + 1 — total prints = n(n+1)/2 for n rows.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: flip parity with 1 - (i % 2) to start rows with zeros.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: continue to Program 41 for a square numbers pyramid.

3. Console Formatting Drills

Practice print vs row newline without complex math.

Example: put console.log(line) inside the inner loop by mistake.

4. Spaced Output

Add spaces between digits once the two-loop structure works.

Example: use line += (i % 2) + " " between digits on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for rows = 5 — total is 15 (5+4+3+2+1).

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i and i % 2 on paper for rows = 3 before coding — watch how parity and row width interact.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Remember Loop Stop Conditions

    Outer loop uses i <= rows; inner loop uses j <= rows starting at j = i.

  2. 2. Validate with Number.isFinite

    Use Number.isFinite(rows) so bad input does not crash when converting rows.

  3. 3. Keep console.log Outside the Inner Loop

    Only call console.log(line) after the inner loop finishes the row.

  4. 4. Modulo for parity

    i % 2 is 1 on odd rows and 0 on even rows — flip with 1 - (i % 2).

  5. 5. Dry-Run rows = 3

    Trace i = 1, 2, 3 on paper before coding the full rows = 5 demo.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put console.log(line) inside the inner loop.

Common Pitfalls

Mistakes that commonly break alternating 1/0 triangles.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use line += i % 2 for digits; console.log(line) only after the inner loop.

  2. 2. Wrong Inner Range

    for (let j = 1; j <= rows; j++) on every row appends a full rectangle — the start must change with i.

    → Keep for (let j = i; j <= rows; j++) so each row shortens correctly.

  3. 3. 0-Based Outer Loop by Mistake

    for (let i = 0; i < rows; i++) shifts parity — row 1 becomes all 0s instead of 1s.

    → Use for (let i = 1; i <= rows; i++) so row 1 starts with 1s.

  4. 4. Forgetting the Row Break

    Omitting console.log(line) glues every digit onto one endless line.

    → Always end the row after the inner loop.

  5. 5. Bare parseInt(prompt())

    Letters or empty input yield NaN with bare parseInt().

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single digit row

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Smallest triangle

Two rows: 11 and 0.

Bad input

Non-numeric input

Bare parseInt(prompt()) yields NaN on bad input — use Number.isFinite first.

Large rows

Large row count

Each row prints rows - i + 1 characters — total work grows as n(n+1)/2.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Rotating number pattern

2. Square numbers pyramid

  • Continue with Program 41
  • Centered pyramid of squares

3. Flip parity

  • Start rows with 0 using 1 - (i % 2)
  • Same loops, inverted output

4. Checkerboard variant

  • Alternate per column with (i + j) % 2
  • Same outer loop, different inner logic

Notes

  • Parity rule. Outer loop: i = 1..rows. Inner loop: for (let j = i; j <= rows; j++). Digit: i % 2.
  • line += i % 2 builds the row; console.log(line) advances — call log only after the inner loop.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Odd rows are all 1s, even rows are all 0s — compare with Program 39 where digits rotate each row.

Quick Takeaway: outer loop i = 1..rows, inner loop for (let j = i; j <= rows; j++) with line += i % 2, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The alternating 1 and 0 triangle is a compact nested-loop lesson: modulo parity picks the row digit while a shrinking inner loop shortens each line. Master the fixed-rows version, then try user input and spaced output.

Practice the three examples above, then continue to Program 41 for the square numbers pyramid.

Odd rows append 1, even rows append 0 — build with line += i % 2 and break with console.log(line).

💡 Best Practices

✅ Do

  • Use for (let i = 1; i <= rows; i++) in the outer loop
  • Inner: for (let j = i; j <= rows; j++) repeats the row digit
  • Use line += i % 2 for digits and console.log(line) after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Number.isFinite(rows) after parseInt(prompt())

❌ Don’t

  • Call console.log(line) inside the inner digit loop
  • Use for (let i = 0; i < rows; i++) for the outer loop (shifts parity)
  • Forget that inner loop must start at j = i
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this alternating 1/0 triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

for (let i = 1; i <= rows; i++)

Code
03

Inner loop

for (let j = i; j <= rows; j++)

Code
% 04

Parity

i % 2 picks digit

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

It appends i % 2 on each row. When i is odd the row is all 1s; when i is even the row is all 0s.
The inner loop runs for (let j = i; j <= rows; j++), appending rows - i + 1 characters per row — decreasing from rows down to 1.
Append 1 - (i % 2) instead of i % 2, or swap the if/else logic.
Program 39 rotates digits 1..rows per row. Program 40 appends only 1 or 0 per row based on parity, with shrinking row length.
Replace 5 with rows in the outer loop bound — see Example 2.
Use line += (i % 2) + " " instead of line += i % 2 — see Example 3.
O(n²) for n rows because total appends are 1 + 2 + ... + n = n(n+1)/2.
Use parseInt with Number.isFinite or validate the raw string before converting so bad input does not produce NaN.
Only one row prints — a single 1 on one line.

Did you Know? 🔊

Odd rows append 1, even rows append 0 — chosen with i % 2. Row i appends rows - i + 1 characters; total appends = n(n+1)/2.

Continue to Program 41

Move on to the square numbers pyramid in the JavaScript number-pattern series.

Program 41 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful