Centered Continuous Number Pyramid in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Spacing + Counter

What You’ll Learn

The centered continuous number pyramid prints 1, then 2 3 4, then 5 6 7 8 9 — a natural step after the mirror pattern in Program 23. This tutorial covers odd row widths, leading spaces, a running counter k, a live preview, algorithm steps, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Centered pyramid

Row 1 prints 1, row 2 prints 2 3 4, row 3 prints 5 6 7 8 9 with leading spaces.

Outer Loop

i += 2

for (let i = 1; i <= maxN; i += 2) sets odd row widths 1, 3, 5.

Spacing + Numbers

if j > i

Reverse loop prints spaces first, then k++ for each number slot.

Running Counter

k never resets

k = 1 before the outer loop; k++ continues across rows.

Live Preview

Odd widths 1–9

Pick a max odd width and draw the centered pyramid instantly in the browser.

O(n²)

Complexity

Each row scans maxN columns; total work scales as .

Introduction

A centered continuous number pyramid prints numbers that keep counting across rows, with leading spaces to center each row. With max width 5, the output is 1, 2 3 4, 5 6 7 8 9 (spaces shown in the worked examples below).

In JavaScript you use an outer loop with odd widths, a reverse inner loop with an if for spaces vs k++, then console.log(line) ends each row.

Why it matters?

It combines spacing logic with a persistent counter — a step up from Program 23’s three inner loops.

Key Highlights

Odd widths

i = 1, 3, 5 controls how many numbers print per row.

Leading spaces

if j > i prints spaces before numbers.

Continuous k

k++ never resets — numbers flow across rows.

Series Foundation

Follow Program 23; continue to Program 25 (bidirectional triangle) next.

In short: for each odd i, scan j from maxN down to 1 — print a space when j > i, else print k then k++, then console.log(line).

📝 Problem & Approach

Given a positive odd max width (e.g. 5), print a centered pyramid where numbers increase continuously across rows using a counter k.

JavaScript
# maxN = 5 (conceptual shape — dots show spaces)
# ··1·
# ·2·3·4
# 5·6·7·8·9

Inputs & Outputs

ItemTypeDescription
maxNintMaximum odd row width — inner loop scans j from maxN down to 1.
iintOuter loop — odd row widths 1, 3, 5 via i += 2.
jintReverse inner loop — spaces when j > i, else print number.
kintRunning counter — starts at 1, increments with k++ across all rows.

Minimal workflow

Pseudocode
k = 1
for i from 1 to maxN step 2:
    line = ""
    for j from maxN down to 1:
        if j > i:
            line += " "
        else:
            line += k; k = k + 1
    console.log(line)

Approach comparison

ApproachIdeaBest for
Spacing + counter1, 2 3 4, 5 6 7 8 9Learning and interviews
User-input maxconst maxN = parseInt(prompt(...), 10)Flexible console programs
Safe inputNumber.isFinite loop + even-width adjustmentRobust user-facing demos

⚡ Quick Reference

GoalPattern
Walk rowsfor (let i = 1; i <= maxN; i += 2)
Init counterk = 1 before the outer loop
Scan columnsfor (let j = maxN; j >= 1; j--)
Space or numberif (j > i) { line += " "; } else { line += k + " "; k++; }
End the rowconsole.log(line)
User inputconst maxN = parseInt(prompt(...), 10)

📋 Fixed maxN vs User Input vs Safe Input

Same centered pyramid — different ways to control width and input validation.

Outer loop
i += 2

Odd row widths 1, 3, 5

Spacing
j > i

Leading spaces center each row

Counter
k++

Numbers continue across rows

Learning tip
if/else

One inner loop handles space vs number

Context

When This Pattern Shows Up

Reach for this pattern when teaching centering with spaces, persistent counters, and if/else inside nested loops.

  1. Post mirror exercise

    Natural follow-up after Program 23 — introduces spacing logic and a running counter.

  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 23 (mirror pattern) and Program 25 (bidirectional 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

Choose an odd max width between 1 and 9 and draw the centered continuous pyramid in the browser.

Try 3, 5, or 7. Even values are adjusted to the nearest odd width. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed max width, user input, and safe input with validation. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print three rows of the centered pyramid with a running counter.

Example 1 — Fixed maxN = 5

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

JavaScript
const maxN = 5;
let k = 1;

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

How It Works

When i = 1, append two spaces then 1 — output 1. When i = 3, append one space then 2 3 4. When i = 5, append 5 6 7 8 9 with no leading spaces. k never resets, so numbers continue across rows.

📈 User Input

Read the maximum odd width with prompt() instead of hard-coding 5.

Example 2 — User Input

Read maxN with prompt() and parseInt(); adjust even widths to the nearest odd value.

JavaScript
const maxInput = prompt("Enter the maximum odd width:");
let maxN = parseInt(maxInput, 10);

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

How It Works

Same spacing + counter core as Example 1; only the source of maxN changes. The even-width adjustment keeps row sizes odd for a proper pyramid shape. Non-numeric input yields NaN with bare parseInt(prompt(), 10) — validate with Number.isFinite for safer labs.

⚡ Safe Input

Use a while loop with Number.isFinite so bad input does not crash the script.

Example 3 — Safe Input with Validation Loop

Validate input before drawing the pyramid — prompt again on failure.

JavaScript
let maxN = 0;

while (maxN < 1) {
  const maxInput = prompt("Enter the maximum odd width:");
  maxN = parseInt(maxInput, 10);
  if (!Number.isFinite(maxN) || maxN < 1) {
    maxN = 0;
    console.log("Please enter a positive whole number.");
  }
}

if (maxN % 2 === 0) {
  maxN--;
}

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

How It Works

The while (maxN < 1) loop re-prompts when input is not a positive integer — then the pyramid draws as usual.

🧠 How the Algorithm Prints Rows

1

Set up

console.log is built in; use prompt() when reading input. Set k = 1 and loop variables i, j.

Setup
2

Outer loop + odd widths

for (let i = 1; i <= maxN; i += 2) — row widths 1, 3, 5 grow the pyramid.

Row
3

Reverse inner loop (j)

for (let j = maxN; j >= 1; j--) scans columns from right to left.

Columns
4

Space or number

if (j > i) appends a space; else line += k + " " and k++.

if/else
5

New line

console.log(line) ends the row after the inner loop.

Break
=

Centered pyramid complete

Numbers continue across rows — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — maxN = 5

Trace each outer-loop value of i, leading spaces, numbers printed, and k after each row.

iLeading spacesNumbers printedk after rowRow output
12 (when j = 5, 4)121
31 (when j = 5)2, 3, 452 3 4
505, 6, 7, 8, 9105 6 7 8 9

Leading spaces per row = (max - i) / 2 when maxN is odd — centers each row.

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: put console.log(line) inside the inner loop by mistake.

2. Pattern Series Base

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

Example: reset k each row and compare output.

3. Console Formatting Drills

Practice line += vs console.log(line) 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: append k + " " with padded widths for 2-digit numbers.

5. Complexity Intuition

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

Example: count printed numbers for maxN = 9 → 1 + 3 + 5 + 7 + 9 = 25.

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-width checks.

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: trace the reverse inner loop on paper for maxN = 3 before coding — spacing bugs hide in the j > i condition.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Do not reset k inside the outer loop unless you want per-row numbering.

  2. 2. Validate prompt()

    Validate parseInt(prompt(), 10) with Number.isFinite so bad input does not produce NaN.

  3. 3. Keep console.log(line) Outside

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

  4. 4. Trace i and j on Paper

    Write each i, space count, and numbers printed before coding.

  5. 5. Dry-Run One Small n

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

Common Pitfalls

Mistakes that commonly break centered pyramid patterns.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use line += " " or line += k + " "; k++; console.log(line) only after the inner loop.

  2. 2. Resetting k Each Row

    Putting k = 1 inside the outer loop restarts numbering — you lose the continuous effect.

    → Initialize k = 1 once before the outer loop unless you want per-row numbering.

  3. 3. Forgetting Leading Spaces

    Without if j > i the pyramid is left-aligned, not centered.

    → Print a space when j > i before printing numbers.

  4. 4. Using Even Row Widths

    Even maxN values break the centering math for this version.

    → Subtract 1 when maxN % 2 == 0, or validate and prompt again.

  5. 5. Unchecked input

    Letters or empty input yield NaN from bare parseInt(prompt(), 10).

    → Validate with Number.isFinite and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

maxN = 1

Single row

Output is just a centered 1 with leading spaces.

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.

Even max

Even width entered

Subtract 1 to force odd width, or re-prompt for an odd value.

Bad input

Non-numeric input

parseInt(prompt(), 10) yields NaN — validate with Number.isFinite first.

maxN = 3

Smallest pyramid

Two rows: centered 1 and 2 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Mirror pattern

2. Bidirectional triangle

3. Reset k per row

  • Move k = 1 inside the outer loop
  • Compare continuous vs per-row numbering

4. Alphabet pyramid

  • Replace numbers with letters using k++ on chars
  • Same spacing logic applies

Notes

  • Centering. Leading spaces when j > i shift numbers right — row width stays at maxN columns.
  • line += stays on the line; console.log(line) advances — mix them carefully.
  • Validate maxN > 0 for interactive programs; maxN = 1 prints a single centered 1.
  • Double-digit numbers need wider spacing — consider fixed-width formatting for large pyramids.

Quick Takeaway: odd outer loop (i += 2), reverse inner loop with if j > i, persistent k++, then console.log(line) after each row.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(n²)O(1)
Safe input (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The centered continuous number pyramid is a compact lesson in spacing and counters: print leading spaces when j > i, then k++ for each number slot. Master the fixed-maxN version, then try user input and safe prompt() validation.

Practice the three examples above, then continue to Program 25 for the bidirectional number triangle.

Never reset k inside the outer loop unless you want per-row numbering — validate maxN when reading from the console.

💡 Best Practices

✅ Do

  • Use for (let i = 1; i <= maxN; i += 2) in the outer loop
  • Initialize k = 1 before the outer loop
  • Print spaces when j > i, else print k and k++
  • Validate parseInt(prompt(), 10) with Number.isFinite before using maxN
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call console.log(line) inside the inner loop
  • Reset k inside the outer loop (unless intentional)
  • Skip leading spaces — the pyramid will be left-aligned
  • Use even maxN without adjustment
  • Ignore bad console input in user-facing demos
  • Skip the maxN = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this pyramid pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer i+=2

Odd widths

Code
+ 03

if j>i

Centering

Code
04

Continuous k

Never reset

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The program appends leading spaces when j > i, which shifts the numbers to the right and centers the pyramid.
Because the counter k is not reset inside the outer loop. It increments with k++ each time a number is appended.
Row widths are odd (1, 3, 5, …) so each row adds two more numbers than the previous row.
line += " " and line += k + " " stay on the same line while building the row. console.log(line) prints the completed row and adds a newline.
The reverse inner loop lets you append leading spaces first (when j > i) and numbers afterward — a common centering trick.
Subtract 1 to force an odd width, or validate and prompt again. This version assumes odd row sizes.
O(n²) for max width n because each row iterates across n columns.
Use parseInt with Number.isFinite in a loop (see Example 3) so bad input does not produce NaN.
Only one row prints — a single centered 1 with leading spaces.

Did you Know? 🔊

This centered pyramid prints numbers continuously using a counter k. An if inside a reverse loop appends leading spaces when j > i, then appends k and does k++ once the column reaches the row boundary.

Continue to Program 25

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

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