JavaScript Number Pyramid Pattern (Centered Continuous)

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

What Is This Pattern?

A centered continuous number pyramid prints odd-width rows with leading spaces, while a shared counter k keeps climbing across every row.

Remember
Rule: odd widths i = 1, 3, 5, …
      space when j > i, else print k++

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

Combines Program 20’s running counter with centering spaces — a natural step after the mirror in Program 23.

How to Solve It

Walk odd widths with i += 2; scan j from maxN down — space if j > i, else print k++.

MethodIdeaBest for
Reverse + ifSpaces then k++ in one loopLearning, interviews
prompt inputSame loops; force odd max if neededInteractive practice
Safe re-promptwhile until valid positive inputRobust labs

Pseudocode

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
    print line (with newline)

Cheat sheet

GoalPattern
Set maxconst maxN = 5;
Init counterlet k = 1; before both loops
Outer loopfor (let i = 1; i <= maxN; i += 2)
Inner reversefor (let j = maxN; j >= 1; j--)
Space vs numberif (j > i) line += " "; else { line += k + " "; k++; }
End rowconsole.log(line);
Force odd maxif (maxN % 2 === 0) maxN--;

Printing Numbers vs Starting a New Line

APIEffectUse for
line += " " / line += k + " "Stays on the same rowSpaces and numbers
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 character group per line.

Live Preview

Change the max odd width and the pyramid updates instantly. Even values are adjusted down by 1.

Whole numbers from 1 to 9. Even inputs become the next lower odd value.

Live result max = 5 · numbers = 9
    1 
  2 3 4 
5 6 7 8 9 

Worked Walkthrough — maxN = 3

Trace each odd i, how many leading spaces, and which values of k are printed.

iSpaces (j > i)NumbersPrinted row
12 (j = 3, 2)11
3none2 3 42 3 4

After two rows, k is 5 — ready for a wider pyramid if maxN grows.

JavaScript Programs

Three complete programs: fixed maxN = 5, prompt input, and a safe re-prompt loop. Use View Output for sample results, or Try It Yourself to edit and run in the playground.

Example 1 — Fixed maxN = 5

Hard-coded odd width — reverse inner loop handles spaces vs k++.

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

1. Odd widths. i runs 1, 3, 5 — those are how many numbers each row prints.

2. Reverse scan. j counts down from maxN; when j > i, append a leading space.

3. Shared counter. Otherwise append k + " " and k++; k survives into the next row.

Example 2 — prompt Input

Read the max width at runtime; if even, subtract 1 so row sizes stay odd.

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

if (!Number.isFinite(maxN) || maxN < 1) {
  console.log("Please enter a positive whole number.");
} else {
  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

1. Prompt and parse. Convert the answer with parseInt(..., 10).

2. Validate and oddify. Reject bad input; if even, maxN-- keeps odd row widths.

3. Same loops. Reverse j scan and shared k match Example 1.

Example 3 — Safe Re-prompt Loop

Keep asking until the user enters a positive whole number, then draw the pyramid.

JavaScript
let maxN = 0;

while (maxN < 1) {
  maxN = parseInt(prompt("Enter the maximum odd width:"), 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

1. Re-prompt. The while loop resets maxN to 0 until input is a positive integer.

2. Then oddify. Even values still drop by 1 before drawing.

3. Same pyramid. The nested loops are unchanged once maxN is ready.

Edge Cases & Pitfalls

Check these before calling the solution done.

k inside

Counter resets

If let k = 1 is inside the outer loop, every row restarts at 1. Keep k outside both loops.

i++

Forgot step 2

Using i++ prints every width 1, 2, 3, … — not only odd pyramid rows. Keep i += 2.

log inside

Broken rows

If console.log is inside the inner loop, spaces and numbers split across lines. Log only after the reverse scan.

even max

Even maximum

With maxN = 6, call maxN-- first so the last width is 5 (odd).

maxN = 1

Single number

Output is just 1 on one line — no leading spaces.

NaN input

Validate parseInt

Letters or empty prompt yield NaN — check Number.isFinite(maxN) && maxN >= 1.

Time and Space Complexity

ProgramTimeExtra space
Examples 1–3O(n²)O(n) for the current line string

About n/2 rows, each scanning n columns → O(n²).

Key Takeaways

  • Rule: odd width i; space when j > i; else print k++.
  • Init once: declare k before the loops so numbers continue across rows.
  • Write vs log: line += … builds; console.log(line) breaks.
  • Complexity: O(n²) for max width n.

One line: grow odd widths, pad with spaces on the left, and never reset the counter between rows.

Frequently Asked Questions

The program appends a space when j > i in the reverse inner loop, which shifts the numbers right and centers each row.
Because the counter k is declared once before the outer loop and increments with k++ every time a number is appended — it never resets.
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 appends leading spaces first (when j > i) and numbers afterward — a common centering trick.
Subtract 1 to force an odd width (see Example 2), or validate and prompt again.
O(n²) for max width n because each row iterates across n columns.
Use parseInt with Number.isFinite, and optionally a while loop that re-prompts on failure (see Example 3).
Only one row prints — a single 1 (with trailing space).

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.

Next: Bidirectional Number Triangle

Continue with the next pattern 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