Odd-Length Descending Number Triangle Pattern in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Step Size Loop

What You’ll Learn

The odd-length descending number triangle teaches how a custom outer-loop step (i -= 2) skips even row widths. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked JavaScript examples, edge cases, and complexity.

Shape Rule

only odd row widths

Row lengths are 7, 5, 3, 1 — each row prints 1 through i with no even-width lines.

Outer Loop

Rows

for (let i = maxN; i >= 1; i -= 2) visits only odd row lengths from the top down.

Inner Loop

1..i ascending

for (let j = 1; j <= i; j++) prints digits 1 through i on every row.

line += j vs console.log(line)

Same line / next line

Digits use line += j; end each row with console.log(line).

Live Preview

1–20 max

Pick an odd maximum and draw the odd-length descending triangle instantly in the browser.

O(n²)

Complexity

Total digit prints still = n(n+1)/2; extra memory stays O(1).

Introduction

An odd-length descending number triangle prints ascending digits on each row, but only for odd row widths. With maxN = 7, the output is 1234567, 12345, 123, 1.

In JavaScript you solve it with a descending outer loop that steps by 2: for (let i = maxN; i >= 1; i -= 2), an inner loop for (let j = 1; j <= i; j++) that appends each digit, then console.log(line) ends each row.

Why it matters?

It shows how changing the loop step creates entirely new shapes — not just different bounds.

Key Highlights

Step by 2

i -= 2 skips even row widths.

Always Ascending

Inner loop always prints 1..i on every row.

Print Then Break

line += j in the inner loop; console.log(line) after.

Series Foundation

Follow Program 13; continue to Program 15 (binary triangle).

In short: for each odd row length i from maxN down to 1 stepping by 2, print 1..i with line += j, then call console.log(line).

📝 Problem & Approach

Given a positive odd integer maxN (or adjusted to odd), print an odd-length descending number triangle: row length i prints digits 1 through i, with the outer loop using i -= 2.

JavaScript
# maxN = 7 (conceptual shape)
# 1234567
# 12345
# 123
# 1
for (let i = maxN; i >= 1; i -= 2)
    for (let j = 1; j <= i; j++)
        line += j   # digits 1..i
    console.log(line)                # next row

Inputs & Outputs

ItemTypeDescription
maxNintMaximum (odd) row width — first row prints 1..maxN.
Printed outputtextOnly odd-length rows; each prints ascending digits 1..i.

Minimal workflow

Pseudocode
for i from maxN down to 1 step -2:
    for j from 1 to i:
        append j to line
    console.log(line)

Approach comparison

ApproachIdeaBest for
i -= 2 outer loopSkip even row widthsLearning and interviews
i-- outer loopPrint every width (7, 6, 5, …, 1)Full descending triangle comparison

⚡ Quick Reference

GoalPattern
Walk odd row lengthsfor (let i = maxN; i >= 1; i -= 2)
Print 1..ifor (let j = 1; j <= i; j++) line += j
End the rowconsole.log(line)
Force odd maxif (maxN % 2 === 0) maxN -= 1
All widths variantfor (let i = maxN; i >= 1; i--) (step by 1)
Program 13 variantif i % 2 == 0 descending else ascending (zigzag)

📋 Step by 2 vs Step by 1 vs Inner Loop

Same family of triangles — different outer-loop steps.

i -= 2
odd only

Prints 7, 5, 3, 1 — skips even widths

i--
all widths

Prints 7, 6, 5, 4, 3, 2, 1 — every row

Inner 1..i
ascending

Always prints digits 1 through i on each row

Learning tip
step first

Master step -2 before comparing with step -1

Context

When This Pattern Shows Up

Reach for this pattern when teaching custom loop steps and skipped iterations.

  1. First lab exercise

    Most JavaScript pattern series start here before pyramids and diamonds.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with prompt() for a flexible row count.

  4. Gateway to variants

    Compare Program 13 (zigzag) and Program 15 (binary triangle) next.

  5. Not a UI layout tool

    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.

🔮 Live Preview

Enter an odd maximum between 1 and 20 and draw the odd-length descending triangle in the browser.

Try 7, 9, or 11. Even values are adjusted down to the nearest odd number.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed maximum, configurable prompt(), and a step-by-1 comparison. Click View Output to reveal sample results, or Try it Yourself to run the code live.

📚 Getting Started

Print four odd-length rows starting from maxN = 7 with a step of -2.

Example 1 — Fixed maxN = 7

Hard-coded height — ideal for first demos and screenshots.

JavaScript
for (let i = 7; i >= 1; i -= 2) {
  let line = "";
  for (let j = 1; j <= i; j++) {
    line += j;
  }
  console.log(line);
}
Try it Yourself

How It Works

When i = 7, the inner loop prints 1234567. When i = 5, it prints 12345, and so on until i = 1 prints 1. The outer loop skips even lengths because of the step -2. console.log(line) after the inner loop starts the next row.

📈 Practical Variant

Let the user choose the maximum row width at runtime.

Example 2 — Configurable Maximum

Read an odd maximum with prompt() and parseInt() (check Number.isFinite in real apps); if the user enters an even number, subtract 1.

JavaScript
let maxN = parseInt(prompt("Enter an odd maximum (e.g., 9):"), 10);

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

How It Works

Same nested-loop core as Example 1; maxN comes from input and is forced odd with if (maxN % 2 === 0) maxN -= 1. Non-numeric input yields NaN with bare parseInt(prompt()) — validate with Number.isFinite for safer labs.

⚡ Full Descending Triangle

Same ascending inner loop, but outer loop steps by 1 to include every width.

Example 3 — Step by 1 (i--)

Print every row width from 7 down to 1 — includes even-length rows for comparison.

JavaScript
const maxN = 7;

for (let i = maxN; i >= 1; i--) {
  let line = "";
  for (let j = 1; j <= i; j++) {
    line += j;
  }
  console.log(line);
}
Try it Yourself

How It Works

Changing the outer step from -2 to -1 (using i--) includes every row width — even lengths like 123456 and 12 appear. Same inner loop; only the outer step changes the shape.

🧠 How the Algorithm Prints Rows

1

Set up

console.log is built in; use prompt() when reading input. Set maxN (fixed or from prompt, forced odd if needed).

Setup
2

Outer loop (odd widths)

for (let i = maxN; i >= 1; i -= 2) picks odd row lengths only; inner loop prints 1..i.

Row
3

Inner loop (1..i)

for (let j = 1; j <= i; j++) prints ascending digits with line += j on every row.

Digits
4

New line

console.log(line) ends the row so the next outer iteration starts fresh.

Break
=

Odd-length triangle complete

Total digit prints: 1+2+…+n = n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — maxN = 7

Trace each outer-loop value of i and note the ascending digits printed on each odd-length row.

iStep from prevInner j rangePrinted row
7start1..71234567
5-21..512345
3-21..3123
1-21..11

Skipped even lengths: 6, 4, 2. Total digit prints: 7+5+3+1 = 16.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change j <= i and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: change i -= 2 to i-- for a full descending triangle.

3. Console Formatting Drills

Practice print vs row newline without complex math.

Example: put console.log(line) inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: print j + " " for spaced digits on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for n = 10 still → 55.

6. Input Validation Labs

Pair the pattern with prompt() return checks and positive-row validation.

Example: reject maxN <= 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.

Advantages

Why this pattern earns a permanent spot in beginner JavaScript courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn step -2 first; compare with step -1 to see how the loop step changes the whole shape.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use maxN and keep i/j for row/column — or rename to row/col.

  2. 2. Validate with Number.isFinite

    Check Number.isFinite(maxN) after parseInt(prompt(), 10) so bad input does not leave maxN unset.

  3. 3. Keep console.log Outside

    Only call console.log(line) after the inner loop finishes the row.

  4. 4. Force Odd Maximum

    if (maxN % 2 === 0) maxN -= 1 keeps the first row odd-length when reading input.

  5. 5. Dry-Run One Small n

    Trace maxN = 7 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.

Common Pitfalls

Mistakes that commonly break odd-length descending number patterns.

  1. 1. Newline Inside the Inner Loop

    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.

  2. 2. Wrong Outer Step

    i-- prints every width; i -= 2 starting from an even maxN skips the intended first row.

    → For odd-only rows, use for (let i = maxN; i >= 1; i -= 2) with odd maxN.

  3. 3. Forgetting the Row Break

    Omitting console.log(line) glues every digit onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Bare parseInt(prompt())

    Letters or empty input return NaN with bare parseInt(prompt(), 10).

    → Check Number.isFinite(maxN) and re-prompt on failure.

  5. 5. Off-by-One on 0-Based Loops

    Switching to a 0-based outer loop without adjusting the stop value can drop the last row or print an empty first row.

    → Prefer for (let i = maxN; i >= 1; i -= 2) with for (let j = 1; j <= i; j++) for the digits.

Edge Cases

Check these inputs before calling the solution done.

maxN = 1

Single digit

Output is just 1 on one line.

maxN = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

maxN < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Many rows

Output grows as n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric prompt()

parseInt(prompt(), 10) returns NaN on bad input — validate first.

Fill char

Even maximum input

Subtract 1 or prompt again — otherwise the first row may not match the odd-only rule.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Zigzag number triangle

  • Alternate direction with i % 2
  • Continue with Program 13

2. Alternating binary triangle

  • Print 0/1 with j % 2 on each row
  • Continue with Program 15

3. Even-width rows only

  • Start at an even maxN and use i -= 2
  • Prints 6, 4, 2, … instead of 7, 5, 3, 1

4. Right-aligned triangle

  • Add leading spaces before each row
  • Harder follow-up after this page

Notes

  • Odd sum. Digit prints for odd widths 1+3+5+…+n still grow as O(n²) for maximum width n.
  • line += j stays on the line; console.log(line) advances — mix them carefully.
  • Validate maxN > 0 for interactive programs; maxN = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop steps by 2 for odd widths, inner loop prints 1..i, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(max²)O(1)
Step by 1 (Example 3)O(max²)O(1)
Wrap Up

🎉 Conclusion

The odd-length descending number triangle is a compact lesson in loop steps: i -= 2 skips even widths while the inner loop always prints 1..i. Master the odd-only version, then compare with i-- for a full descending triangle.

Practice the three examples above, then continue to Program 15 for the alternating binary triangle.

Use for (let i = maxN; i >= 1; i -= 2) for odd-only rows and for (let j = 1; j <= i; j++) for ascending digits — validate maxN when reading input.

💡 Best Practices

✅ Do

  • Explain step -2 skips even widths before coding
  • Use line += j for digits and console.log(line) after each row
  • Validate maxN ≥ 1 for interactive programs
  • Check Number.isFinite(maxN) after parseInt(prompt(), 10) before using maxN
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call console.log(line) inside the inner digit loop
  • Use i-- when you meant odd-only rows
  • Skip the newline after each row
  • Ignore bad console input in user-facing demos
  • Skip the maxN = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this odd-length pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Steps by 2 downward

Code
2 03

Inner loop

Always prints 1..i

Code
04

Newline

Ends each row

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The outer loop uses for (let i = maxN; i >= 1; i -= 2), so it visits only odd widths: 7, 5, 3, 1. Even lengths like 6, 4, 2 are skipped.
Because the step of -2 skips even row lengths. After 1234567 (7 digits), the next row is 5 digits (12345), not 6.
line += j stays on the same row while building digits. console.log(line) prints the completed row and adds a newline. Digits use += inside the inner loop; the row break uses console.log after the inner loop.
Change the outer loop to for (let i = maxN; i >= 1; i--). Then you print 7, 6, 5, 4, 3, 2, 1 — every width.
Program 13 alternates ascending/descending direction with i % 2 (12345, 4321, 123, 21, 1). Program 14 always prints 1..i but only for odd row lengths using a step of -2.
O(n²) where n is the maximum row width. You print about 1+3+5+…+n odd-width digits, which is still O(n²).
Subtract 1 to make it odd (e.g. if maxN % 2 === 0 maxN -= 1) so the first row stays odd-length, or document that even input shifts the pattern.
Use parseInt with Number.isFinite and a maxN > 0 check after prompt(), or validate the raw string before converting 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? 🔊

Only odd-length rows print. The outer loop uses i -= 2 (7, 5, 3, 1) and the inner loop prints 1..i — still O(n²) total digit prints for maximum width n.

Continue to Program 15

Move on to the alternating binary number triangle in the JavaScript number-pattern series.

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