JavaScript Number Triangle Pattern (Odd/Even Rows)

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

What Is This Pattern?

An alternating odd/even triangle grows one number per row while switching sequences by row parity — odd rows print odds from 1, even rows print evens from 2.

Remember
Rule: for i = 1 to n
        k = 1 if i odd, else 2
        print k, then k += 2, i times

1
2 4
1 3 5
2 4 6 8
1 3 5 7 9     ← n = 5

Builds on Program 17’s odd sequences — here row parity chooses whether the whole row stays odd or even.

How to Solve It

Grow row length from 1 to n; set start k from i % 2, then step k += 2.

MethodIdeaBest for
if/else startOdd → k = 1; even → k = 2Learning, interviews
prompt + ternaryk = (i % 2 === 0) ? 2 : 1Interactive practice
Flip paritySwap starts so odd rows print evensVariant practice

Pseudocode

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

Cheat sheet

GoalPattern
Set sizeconst n = 5;
Outer loopfor (let i = 1; i <= n; i++)
Pick startlet k = (i % 2 === 0) ? 2 : 1;
Inner loopline += k + " "; k += 2;
End rowconsole.log(line);
Flip parityk = (i % 2 === 0) ? 1 : 2;

Printing Numbers vs Starting a New Line

APIEffectUse for
line += k + " "Stays on the same rowEach spaced number
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 number per line.

Live Preview

Change n and the alternating odd/even 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 · numbers = 15
1 
2 4 
1 3 5 
2 4 6 8 
1 3 5 7 9 

Worked Walkthrough — n = 3

Trace each outer value of i, the start k, and the spaced numbers printed.

iStart kValuesPrinted row
11 (odd)11
22 (even)2, 42 4
31 (odd)1, 3, 51 3 5

As i grows, more k += 2 steps run — the row stays odd-only or even-only.

JavaScript Programs

Three complete programs: fixed n = 5, prompt with a ternary start, and flipped row parity. 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 — if/else picks start; inner loop appends k then steps by 2.

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let k;
  if (i % 2 === 0) {
    k = 2;
  } else {
    k = 1;
  }

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

How It Works

1. Outer loop. i runs from 1 to n — the count of numbers on that row.

2. Pick start. Even i sets k = 2; odd i sets k = 1.

3. Inner loop. Append k + " ", then k += 2, repeated i times; console.log(line) ends the row.

Example 2 — prompt Input

Read n at runtime; use a ternary for the start value.

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 k = (i % 2 === 0) ? 2 : 1;
    let line = "";
    for (let j = 1; j <= i; j++) {
      line += k + " ";
      k += 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. Compact start. (i % 2 === 0) ? 2 : 1 replaces the if/else — same shape as Example 1.

Example 3 — Flipped Row Parity

Even rows print odds; odd rows print evens — only the start assignment swaps.

JavaScript
const n = 5;

for (let i = 1; i <= n; i++) {
  let k;
  if (i % 2 === 0) {
    k = 1;
  } else {
    k = 2;
  }

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

How It Works

1. Swap starts. Even i gets k = 1; odd i gets k = 2.

2. Same step. Inner loop and k += 2 stay unchanged.

3. Mirrored rows. Row 1 becomes 2; even rows now print odds.

Edge Cases & Pitfalls

Check these before calling the solution done.

log inside

Vertical numbers

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

k++

Mixed parity

Using k++ instead of k += 2 mixes odds and evens on the same row.

Wrong start

Flipped shape

Swapping the if/else starts yields Example 3 — still valid, but not the sample output.

n = 1

Single number

Output is just 1 (with a trailing space) 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 numbers printed: 1 + 2 + … + n = n(n+1)/2 → still O(n²).

Key Takeaways

  • Rule: odd rows start at 1; even rows at 2; then k += 2.
  • Vs Program 17: parity chooses the whole row, not a left-shifted odd list.
  • Write vs log: line += k + " " builds; console.log(line) breaks.
  • Complexity: O(n²) for n rows.

One line: grow the row from 1 to n, pick odd or even start from parity, then step by 2.

Frequently Asked Questions

We check i % 2. If i is odd, set k = 1 for odd numbers; if i is even, set k = 2 for even numbers.
Row 2 is even, so k starts at 2. The inner loop appends k then adds 2 twice: 2, then 4.
line += k + " " stays on the same row with a trailing space. console.log(line) prints the completed row and adds a newline.
After appending k, update k += 2 so the sequence stays odd or even while increasing.
Yes. Swap the condition so even rows start at 1 and odd rows start at 2 — see Example 3.
O(n²) for n rows. Total numbers printed 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?

Row parity picks the start value: odd rows begin at 1, even rows at 2. Then k += 2 keeps each row odd-only or even-only — still O(n²) total appends for n rows.

Next: Fill with 5 Triangle

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

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