JavaScript Number Triangle Pattern (Alternating Direction)

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

What Is This Pattern?

An alternating number triangle prints i continuous numbers on row i: ascending on odd rows, descending on even rows.

Remember
Rule: odd → ascending, even → descending (running counter)

1
3 2
4 5 6
10 9 8 7
11 12 13 14 15   ← rows = 5

Unlike Program 50 (fixed digit sequences), numbers stay continuous — total values = n(n+1)/2.

How to Solve It

Keep a counter nxt. On odd rows append ascending; on even rows start from end and descend.

MethodIdeaBest for
Odd/even + counteri % 2 picks direction; nxt never resetsClassic zig-zag demos
CompactSame logic with fewer rows (e.g. 3)Quick dry-runs

Pseudocode

Pseudocode
nxt = 1
for i from 1 to rows:
    end = nxt + i - 1
    line = ""
    repeat i times:
        if i is odd:
            append nxt
        else:
            append end; end -= 1
        nxt += 1
    print line

Cheat sheet

GoalPattern
Outer (rows)for (let i = 1; i <= rows; i++)
Row end valuelet end = nxt + i - 1;
Odd (ascending)line += nxt + " ";
Even (descending)line += end + " "; end--;
Advance counternxt++; once per printed value
End the rowconsole.log(line.trim());
Total numbersrows * (rows + 1) / 2

Printing Numbers vs Starting a New Line

APIEffectUse for
line += …Stays on the same rowEach number on the row
console.log(line)Ends the current rowAfter all i numbers finish

Append without a newline, then end the row once.

Live Preview

Change the row count and the alternating triangle updates instantly.

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

Live result rows = 5 · 15 numbers
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15

Worked Walkthrough

Trace three rows when rows = 5 — watch nxt, end, and direction.

Row iDirectionnxt startendPrinted row
1Odd ↑111
2Even ↓233 2
3Odd ↑464 5 6

After row 2, nxt is 4 — so row 3 starts at 4 and continues ascending.

JavaScript Programs

Three complete programs: fixed rows = 5, prompt input, and a compact rows = 3 demo. Use View Output for samples, or Try It Yourself to edit and run live.

Example 1 — Fixed rows = 5

Odd rows ascend with nxt; even rows descend from end.

JavaScript
const rows = 5;
let nxt = 1;

for (let i = 1; i <= rows; i++) {
  let end = nxt + i - 1;
  let line = "";

  for (let j = 0; j < i; j++) {
    if (i % 2 === 1) {
      line += nxt + " ";
    } else {
      line += end + " ";
      end--;
    }
    nxt++;
  }

  console.log(line.trim());
}
Try It Yourself

How It Works

1. Counter never resets. nxt starts at 1 and advances once per printed value across every row.

2. Odd rows ascend. Append nxt left-to-right — row 1 is 1, row 3 is 4 5 6.

3. Even rows descend. Set end = nxt + i - 1, then append while decrementing — row 2 is 3 2.

Example 2 — User Input Rows

Read rows with prompt and validate before drawing.

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

if (!Number.isFinite(rows) || rows < 1) {
  console.log("Please enter a positive integer.");
} else {
  let nxt = 1;

  for (let i = 1; i <= rows; i++) {
    let end = nxt + i - 1;
    let line = "";

    for (let j = 0; j < i; j++) {
      if (i % 2 === 1) {
        line += nxt + " ";
      } else {
        line += end + " ";
        end--;
      }
      nxt++;
    }

    console.log(line.trim());
  }
}
Try It Yourself

How It Works

1. Prompt and validate. Use parseInt and require rows >= 1.

2. Same odd/even core. Only the source of rows changes — counter and direction match Example 1.

3. Entering 4. Ten numbers total (4×5/2), last row 10 9 8 7.

Example 3 — Compact rows = 3

Same alternating logic with fewer rows for a quick visual check.

JavaScript
const rows = 3;
let nxt = 1;

for (let i = 1; i <= rows; i++) {
  let end = nxt + i - 1;
  let line = "";

  for (let j = 0; j < i; j++) {
    if (i % 2 === 1) {
      line += nxt + " ";
    } else {
      line += end + " ";
      end--;
    }
    nxt++;
  }

  console.log(line.trim());
}
Try It Yourself

How It Works

1. Shrink the size. Only rows changes — still odd ascend / even descend.

2. Easier to trace. Six numbers total — useful while learning nxt and end.

3. Same continuity rule. nxt still never resets between rows.

Edge Cases & Pitfalls

Check these before calling the solution done.

Counter

Never reset nxt between rows

Resetting breaks continuity — row 3 would restart at 1 instead of 4.

Even rows

Compute end before the inner loop

Use end = nxt + i - 1, then decrement while appending.

rows = 1

Single-row case

Output is just 1 — one ascending value on an odd row.

Bad input

Validate parseInt

Check Number.isFinite(rows) and require rows >= 1 before the loops.

Time and Space Complexity

ProgramTimeExtra space
Fixed / compact (Examples 1, 3)O(n²)O(n) per row string
User input (Example 2)O(n²)O(n) per row string

Total printed numbers are 1 + 2 + … + n = n(n+1)/2 — still quadratic in n.

Key Takeaways

  • Rule: odd rows ascend, even rows descend — one continuous counter.
  • Even rows: start from end = nxt + i - 1, then decrement.
  • Break the row: call console.log only after all i numbers finish.
  • Complexity: O(n²) — triangular count of values.

One line: keep a running counter; print ascending on odd rows and descending on even rows.

Frequently Asked Questions

Row 2 is even, so it logs right-to-left. The numbers 2 and 3 belong on that row, but they appear as 3 2.
A running counter nxt increments once per printed value and is never reset between rows.
Before printing row i, end = nxt + i - 1. That is the rightmost value when logging in reverse.
line += appends on the same row. console.log(line) ends the row after all i numbers are appended.
Program 50 concatenates fixed digit sequences per row. Program 51 uses a continuous counter and alternates direction on odd/even rows.
O(n²) for n rows because total printed numbers are 1+2+…+n = n(n+1)/2.
Yes — build with a trailing space then trim, or join an array with spaces before console.log.
One row prints 1 — a single ascending value on the first odd row.

Did you know?

Numbers stay continuous via a running counter nxt. Odd rows append ascending; even rows append descending with end = nxt + i - 1. Row 2 shows 3 2 — total values = n(n+1)/2.

Next: Increasing-Decreasing Number Pyramid

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

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