Shape Rule
odd i: 1..i, even i: i..1
Row length 5 prints 12345; length 4 prints 4321; length 3 prints 123, and so on.

The alternating zigzag number triangle combines nested loops with an if/else parity check to flip print direction each row. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked JavaScript examples, edge cases, and complexity.
odd i: 1..i, even i: i..1
Row length 5 prints 12345; length 4 prints 4321; length 3 prints 123, and so on.
Rows
for (let i = rows; i >= 1; i--) walks each line from the longest down to a single digit.
if / else
if (i % 2 === 0) prints descending; else prints ascending with line += j.
Same line / next line
Digits use line += j; end each row with console.log(line).
1–20 rows
Pick a row count and draw the zigzag number triangle instantly in the browser.
Complexity
Total digit prints still = n(n+1)/2; extra memory stays O(1).
An alternating zigzag number triangle shrinks each row while flipping print direction based on row length parity. With rows = 5, the output is 12345, 4321, 123, 21, 1.
In JavaScript you solve it with a descending outer loop plus an if/else: odd i uses for (let j = 1; j <= i; j++), even i uses for (let j = i; j >= 1; j--), then console.log(line) ends each row.
It introduces conditions inside loops — a stepping stone from pure nested loops to logic-heavy pattern problems.
Odd i prints 1..i; even i prints i..1.
i % 2 picks ascending vs descending inner loop.
line += j in the inner loop; console.log(line) after.
Follow Program 12; continue to Program 14 (odd-length rows).
In short: for each row length i from rows down to 1, use i % 2 to print 1..i or i..1, then call console.log(line).
Given a positive integer rows, print an alternating zigzag number triangle: row length i prints digits ascending when i is odd and descending when i is even, with the outer loop counting from rows down to 1.
# First 5 rows (conceptual shape)
# 12345
# 4321
# 123
# 21
# 1
for (let i = rows; i >= 1; i--)
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) | Item | Type | Description |
|---|---|---|
rows | int | Number of triangle lines to print (typically ≥ 1). |
| Printed output | text | Each row prints sequential digits; odd-length rows ascend, even-length rows descend. |
for i from rows down to 1:
if i is even:
for j from i down to 1: append j to line
else:
for j from 1 to i: append j to line
console.log(line) | Approach | Idea | Best for |
|---|---|---|
| if/else + nested loops | Parity branch + inner direction | Learning and interviews |
| Direction variables | Compute start, end, step from parity | Shorter production-style demos |
| Goal | Pattern |
|---|---|
| Walk each row | for (let i = rows; i >= 1; i--) |
| Odd row: ascending | for (let j = 1; j <= i; j++) line += j |
| Even row: descending | for (let j = i; j >= 1; j--) line += j |
| Parity check | if (i % 2 == 0) { ... } else { ... } |
| End the row | console.log(line) |
| Program 12 variant | for (let j = i; j <= rows; j++) line += i (repeating digits) |
Same zigzag triangle — different ways to pick inner-loop direction.
1..iPrints 123 when row length is 3
i..1Prints 4321 when row length is 4
parityEven i reverses; odd i goes forward
if/else firstMaster explicit branches before direction variables
Reach for this pattern when teaching conditions inside nested loops.
Most JavaScript pattern series start here before pyramids and diamonds.
Outer/inner bound practice with an immediate visual check.
Combine loops with prompt() for a flexible row count.
Compare Program 12 (11111, 2222, …) and Program 14 (odd-length rows) next.
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.
Choose a row count between 1 and 20 and draw the alternating zigzag number triangle in the browser.
Three complete JavaScript programs — fixed row count, prompt(), and a direction-variables refactor. Click View Output to reveal sample results, or Try it Yourself to run the code live.
Print five rows of the alternating zigzag number triangle with if/else branches.
rows = 5Hard-coded height — odd rows ascend, even rows descend.
const rows = 5;
for (let i = rows; 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);
} When i = 5 (odd), the inner loop prints 12345. When i = 4 (even), it prints 4321, and so on until i = 1 prints 1. console.log(line) after the inner loop starts the next row.
Let the user choose the height at runtime.
Read the row count with prompt() and parseInt() (check Number.isFinite in real apps).
const rowsInput = prompt("Enter the number of rows:");
const rows = parseInt(rowsInput, 10);
if (!Number.isFinite(rows) || rows <= 0) {
console.log("Please enter a positive integer.");
} else {
for (let i = rows; 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);
}
} Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input yields NaN with bare parseInt(prompt()) — validate with Number.isFinite for safer labs.
Same zigzag shape with one inner loop and computed start/end/step.
Replace the if/else blocks with start, end, and step values derived from parity.
const rows = 5;
for (let i = rows; 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);
} start, end, and step encode the same ascending/descending logic as the if/else version in one inner loop. Great once you understand parity branching; keep the explicit if/else for exams that ask you to show both inner loops.
console.log is built in; use prompt() when reading input. Set rows (fixed or from prompt).
for (let i = rows; i >= 1; i--) picks the row length; parity decides print direction.
if (i % 2 === 0) runs descending j; else runs ascending j with line += j.
console.log(line) ends the row so the next outer iteration starts fresh.
Total digit prints: 1+2+…+n = n(n+1)/2 — O(n²) time, O(1) extra memory.
rows = 4Trace each outer-loop value of i and note whether the row prints ascending or descending.
i | Parity | Inner j range | Printed row |
|---|---|---|---|
4 | even | 4..1 | 4321 |
3 | odd | 1..3 | 123 |
2 | even | 2..1 | 21 |
1 | odd | 1..1 | 1 |
Total digit prints: 1 + 2 + 3 + 4 = 10 = 4×5/2.
Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.
Clearest visual proof that outer and inner bounds interact.
Example: change j <= i and watch the shape change.
Foundation for inverted, pyramid, diamond, and hollow variants.
Example: swap if/else branches to flip odd/even direction.
Practice print vs row newline without complex math.
Example: put console.log(line) inside the inner loop by mistake.
Swap digits for letters, stars, or spaced output once the loop works.
Example: print j + " " for spaced digits on each row.
Triangular totals make O(n²) concrete for beginners.
Example: count printed digits for n = 10 still → 55.
Pair the pattern with prompt() 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.
Why this pattern earns a permanent spot in beginner C courses.
Wrong bounds show up immediately as a broken staircase.
Only loops and console output — no arrays or math libraries.
Invert, center, hollow, or change the fill character with small edits.
Streaming output needs no storage beyond loop counters.
Pro Tip: learn the if/else version first; treat direction variables as a polish refactor afterward.
Small habits that keep number-pattern code clean.
Use rows (or n) and keep i/j for row/column — or rename to row/col.
Number.isFiniteAvoid crashes when the user types letters instead of a number.
Only call console.log(line) after the inner loop finishes the row.
if (i % 2 == 0) is the standard parity check for zigzag rows.
Trace rows = 3 on paper before coding larger demos.
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.
Mistakes that commonly break alternating zigzag number patterns.
Each digit lands on its own line — you get a column, not a triangle.
→ Use line += j for digits; console.log(line) only after the inner loop.
Using ascending on even rows or descending on odd rows reverses the zigzag.
→ Even i: for (let j = i; j >= 1; j--). Odd i: for (let j = 1; j <= i; j++).
Omitting console.log(line) glues every digit onto one endless line.
→ Always end the row after the inner loop.
Letters or empty input return NaN with bare parseInt(prompt(), 10).
→ Check Number.isFinite(rows) and re-prompt on failure.
Switching to i = 0 without adjusting the row length and parity check prints an empty first row or wrong direction.
→ Prefer 1-based for (let i = rows; i >= 1; i--) with the same even/odd branches, or carefully map both if you go 0-based.
Check these inputs before calling the solution done.
Output is just 1 on one line.
Outer loop never runs — print nothing or show a message.
rows < 0Treat as invalid; re-prompt instead of silent empty output.
Output grows as n²/2 characters — fine for labs, noisy for huge n.
parseInt(prompt(), 10) returns NaN on bad input — validate first.
Swapping if/else still works — output direction mirrors, not broken.
Try these variations to lock in the pattern.
i with for (let j = i; j <= rows; j++)line += j between digitsn(n+1)/2 — hence O(n²) time.line += j stays on the line; console.log(line) advances — mix them carefully.rows > 0 for interactive programs; rows = 1 should print a single 1.Quick Takeaway: outer loop sets row length, i % 2 picks ascending or descending inner loop, then break the line.
| Program | Time | Extra space |
|---|---|---|
| Nested loops (Examples 1–2) | O(rows²) | O(1) |
| Direction variables (Example 3) | O(rows²) | O(1) |
The alternating zigzag number triangle combines nested loops with parity branching — a natural step after repeating-digit patterns. Master the if/else version, then optionally refactor rows with start/stop/step direction variables.
Practice the three examples above, then continue to Program 14 for odd-length descending rows.
Odd i prints 1..i; even i prints i..1 — keep line += j for digits and console.log(line) for the break.
line += j for digits and console.log(line) after each rowrows ≥ 1 for interactive programsNumber.isFinite(rows) after parseInt(prompt(), 10) before using rowsconsole.log(line) inside the inner digit looprows = 1 edge casePrint the pattern the beginner-friendly way.
Odd i: 1..i; even i: i..1
DefinitionControls row length each line
Codei % 2 picks direction
Ends each row
I/OO(n²) time
AnalysisOdd row length i prints 1..i; even row length prints i..1. The outer loop shrinks from rows to 1, and i % 2 flips direction — still O(n²) total digit prints.
Move on to the odd-length descending number triangle in the JavaScript number-pattern series.
12 people found this page helpful