JavaScript Binary Number Triangle Pattern (Alternating)

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

An alternating binary triangle grows one digit per row while printing 0 and 1 from j % 2 — 1, 01, 101, 0101, …

Remember
Rule: for i = 1 to n
        for j = i down to 1
          print j % 2

1
01
101
0101
10101     ← n = 5

The descending inner loop sets the starting bit of each row — Program 16 counts up instead and gets a different first bit on even rows.

How to Solve It

Grow row length from 1 to n; on each row, count j down and append j % 2.

MethodIdeaBest for
Nested loopsOuter grows; inner j % 2 descendingLearning, interviews
Flip parity1 - (j % 2) starts with 0Variant practice
prompt inputSame loops; read n at runtimeInteractive practice

Pseudocode

Pseudocode
for i from 1 to n:
    line = ""
    for j from i down to 1:
        line += (j % 2)
    print line (with newline)

Cheat sheet

GoalPattern
Set sizeconst n = 5;
Outer loopfor (let i = 1; i <= n; i++)
Inner loopfor (let j = i; j >= 1; j--) line += j % 2;
End rowconsole.log(line);
Binary digitj % 2 → 0 or 1
Flip bitsline += 1 - (j % 2);

Printing Numbers vs Starting a New Line

APIEffectUse for
line += j % 2Stays on the same rowEach binary digit
console.log(line)Ends the lineAfter the inner loop

Build the row with +=, then break once with console.log. Putting console.log inside the inner loop prints one digit per line.

Live Preview

Change n and the alternating binary triangle updates instantly.

Whole numbers from 1 to 9. Tap a chip or type a value — the preview redraws as you go.

Live result n = 5 · digits = 15
1
01
101
0101
10101

JavaScript Programs

Three complete programs: fixed n = 5, a flipped-parity variant, and prompt input. Use View Output for sample results, or Try It Yourself to edit and run in the playground.

Example 1 — Fixed n = 5

Hard-coded height — outer grows; inner appends j % 2 while counting down.

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let line = "";
  for (let j = i; j >= 1; j--) {
    line += j % 2;
  }
  console.log(line);
}
Try It Yourself

How It Works

1. Outer loop. i runs from 1 to n — the length of that row.

2. Inner loop. j counts from i down to 1; line += j % 2 appends 0 or 1.

3. Newline. console.log(line) after the inner loop prints the row and starts the next one.

Example 2 — Flip with 1 - (j % 2)

Invert every bit so the first row starts with 0 instead of 1.

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let line = "";
  for (let j = i; j >= 1; j--) {
    line += 1 - (j % 2);
  }
  console.log(line);
}
Try It Yourself

How It Works

1. Same loops. Outer and inner bounds match Example 1.

2. Flip the bit. 1 - (j % 2) turns 1 into 0 and 0 into 1.

3. Mirrored start. Row 1 becomes 0; even rows now start with 1.

Example 3 — prompt Input

Read n at runtime with prompt and parseInt.

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

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

How It Works

1. Prompt and parse. Convert the answer with parseInt(..., 10).

2. Validate first. Reject NaN or non-positive values before looping.

3. Same binary logic. Only the source of n changes — still j % 2 while counting down.

Edge Cases & Pitfalls

Check these before calling the solution done.

log inside

Vertical digits

If console.log is inside the inner loop, each bit lands on its own line. Append with +=; log only after the inner loop.

j = 1..i

Program 16 shape

Counting j up instead of down yields 1, 10, 101, 1010 — that is Program 16.

print(j)

Not binary

Appending j instead of j % 2 prints a countdown, not 0/1 bits.

n = 1

Single bit

Output is just 1 on one line.

n ≤ 0

Empty output

The outer loop never runs. Guard prompt input with n >= 1.

NaN input

Validate parseInt

Letters or empty prompt yield NaN — check Number.isFinite(n) && n >= 1.

Time and Space Complexity

ProgramTimeExtra space
Examples 1–3O(n²)O(n) for the current line string

Total digits printed: 1 + 2 + … + n = n(n+1)/2 → still O(n²).

Key Takeaways

  • Rule: outer i = 1..n; inner j = i..1 appends j % 2.
  • Vs Program 16: descending j flips the starting bit on even rows.
  • Write vs log: line += j % 2 builds; console.log(line) breaks.
  • Complexity: O(n²) for n rows.

One line: grow the row from 1 to n, and append each descending index modulo 2.

Frequently Asked Questions

Modulo 2 returns the remainder after dividing by 2. Any integer is either even (remainder 0) or odd (remainder 1).
On row 2, the inner loop prints j = 2 then j = 1. That becomes 2 % 2 = 0 then 1 % 2 = 1, so the row is 01.
line += j % 2 stays on the same row while building binary digits. console.log(line) prints the completed row and adds a newline.
Program 15 counts the inner loop down (j = i..1) producing 1, 01, 101, 0101. Program 16 counts up (j = 1..i) producing 1, 10, 101, 1010.
Yes. Use 1 - (j % 2) instead of j % 2 to flip every digit — first row becomes 0 instead of 1.
O(n²) where n is the number of rows. Total digit appends equal 1+2+…+n = n(n+1)/2.
Use parseInt(prompt(...), 10) and check Number.isFinite(n) && n >= 1 so bad input does not produce NaN.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you know?

Each row prints alternating 0 and 1 using j % 2. The inner loop counts down with for (let j = i; j >= 1; j--), so row length grows each line — still O(n²) total prints.

Next: Column-Wise Alternating Binary

Continue with the next pattern in the JavaScript number-pattern series.

Program 16 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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