JavaScript Alternating Number Triangle Pattern (Zigzag)

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

What Is This Pattern?

An alternating zigzag triangle shrinks each row while flipping print direction — odd lengths ascend 1..i, even lengths descend i..1.

Remember
Rule: for i = n down to 1
        if i is odd  → print 1..i
        if i is even → print i..1

12345
4321
123
21
1         ← n = 5

Combines a shrinking outer loop with an if/else on i % 2 — sequential digits, not repeated ones like Program 12.

How to Solve It

Shrink row length from n; use parity to choose ascending or descending digits.

MethodIdeaBest for
if/else branchesOdd → 1..i; even → i..1Learning, interviews
prompt inputSame logic; read n at runtimeInteractive practice
Direction varsOne inner loop with start/end/stepCleaner refactor

Pseudocode

Pseudocode
for i from n down to 1:
    line = ""
    if i is even:
        for j from i down to 1:
            line += j
    else:
        for j from 1 to i:
            line += j
    print line (with newline)

Cheat sheet

GoalPattern
Set sizeconst n = 5;
Outer loopfor (let i = n; i >= 1; i--)
Odd rowfor (let j = 1; j <= i; j++) line += j;
Even rowfor (let j = i; j >= 1; j--) line += j;
Parity testi % 2 === 0
End rowconsole.log(line);

Printing Numbers vs Starting a New Line

APIEffectUse for
line += jStays on the same rowEach sequential 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 zigzag 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
12345
4321
123
21
1

Worked Walkthrough — n = 3

Trace each outer value of i, its parity, and the printed direction.

iParityDirectionPrinted row
3odd1..3123
2even2..121
1odd1..11

As i drops, rows shorten; i % 2 flips ascending vs descending.

JavaScript Programs

Three complete programs: fixed n = 5, prompt input, and a direction-variable refactor. 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 shrinks; if/else picks ascending or descending digits.

JavaScript
const n = 5;

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

How It Works

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

2. Parity branch. Even i prints i..1; odd i prints 1..i via line += j.

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

Example 2 — 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 = n; i >= 1; i--) {
    let line = "";
    if (i % 2 === 0) {
      for (let j = i; j >= 1; j--) {
        line += j;
      }
    } else {
      for (let j = 1; j <= i; j++) {
        line += j;
      }
    }
    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 zigzag. Only the source of n changes — parity still flips direction.

Example 3 — Direction Variables

One inner loop — start, end, and step encode the same parity rule.

JavaScript
const n = 5;

for (let i = n; i >= 1; i--) {
  let line = "";
  const descending = i % 2 === 0;
  const start = descending ? i : 1;
  const end = descending ? 1 : i;
  const step = descending ? -1 : 1;
  for (let j = start; descending ? j >= end : j <= end; j += step) {
    line += j;
  }
  console.log(line);
}
Try It Yourself

How It Works

1. Compute direction. Even i sets descending start/end/step; odd i sets ascending.

2. One inner loop. The same for walks either way using those three values.

3. Same shape. Output matches Examples 1–2 — useful once the if/else rule is clear.

Edge Cases & Pitfalls

Check these before calling the solution done.

log inside

Vertical digits

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

print(i)

Repeated digit

Appending i instead of j prints a repeated digit, not a sequence — that is Program 11/12 territory.

Wrong parity

Mirrored zigzag

Swapping the if/else branches flips which rows ascend — still valid, but not the sample output.

n = 1

Single digit

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–2O(n²)O(n) for the current line string
Direction vars (Example 3)O(n²)O(n) for the current line string

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

Key Takeaways

  • Rule: outer i = n..1; odd → 1..i, even → i..1.
  • Vs Program 12: sequential digits + parity flip, not repeated digits.
  • Write vs log: line += j builds; console.log(line) breaks.
  • Complexity: O(n²) for n rows.

One line: shrink the row from n, and let i % 2 choose ascending or descending digits.

Frequently Asked Questions

The program checks whether i is even or odd. For odd i it prints 1..i ascending; for even i it prints i..1 descending, creating a zigzag direction.
The second row from the top has length i = 4, which is even. The even branch runs for (let j = i; j >= 1; j--) and prints 4, 3, 2, 1.
line += j stays on the same row while building digits. console.log(line) prints the completed row and adds a newline.
Program 12 repeats the row digit (11111, 2222, 333). Program 13 prints sequential digits 1..i or i..1 and alternates direction using i % 2.
O(n²) where n is the number of rows. Total digit appends equal n+(n−1)+…+1 = n(n+1)/2.
Yes. Swap the if and else branches so odd rows descend and even rows ascend — the zigzag still works, just mirrored.
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?

Odd row length i prints 1..i; even row length prints i..1. The outer loop shrinks from n to 1, and i % 2 flips direction — still O(n²) total digit prints.

Next: Odd-Length Descending Pyramid

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

Program 14 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