Concentric Number Square in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Symmetry

What You’ll Learn

Program 46 prints a concentric number square: outer values stay at k while inner layers step down to 1 at the center — a natural step after Program 45’s star-and-zero X grid. This tutorial covers nested loops with j > i logic, left/right mirroring, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Layers to center

Each row i prints numbers that peel from k down to i, then mirror back out.

Outer Loop

i = k..1

for (let i = k; i >= 1; i--) walks each concentric layer from outside in.

Two Inner Loops

Left + right

j = k..1 builds the left half; j = 2..k mirrors the right half.

Cell Rule

j > i

j > i ? j : i — append outer column j or current layer i.

Live Preview

k = 3..7

Pick outer value k and draw the concentric square in the browser.

O(k²)

Complexity

k rows × 2k - 1 columns — total prints grow as ; extra memory stays O(1).

Introduction

A concentric number square prints layers of numbers that decrease toward the center and mirror back out symmetrically. With k = 5, the outer row is all 5s and the bottom row ends at 1 in the middle.

In JavaScript the outer loop runs i = k..1, two inner loops build left and right halves, and j > i picks the outer column value or the current row value via line +=.

Why it matters?

It teaches symmetric row building and layer logic — a key step after Program 45’s star-and-zero X grid.

Key Highlights

Outer value k

Sets max number and width.

Left + right

Two inner loops mirror halves.

vs Program 45

Program 45 prints * and 0; Program 46 prints concentric numbers.

Series Foundation

Follow Program 45; continue to Program 47 next.

In short: outer loop i = k..1, two inner loops, append j if j > i else i, then console.log(line).

📝 Problem & Approach

Given outer value k = 5, print a concentric number square — layers decrease to 1 at the center and mirror back out.

JavaScript
# k = 5
//5 5 5 5 5 5 5 5 5
//5 4 4 4 4 4 4 4 5
//5 4 3 3 3 3 3 4 5
//5 4 3 2 2 2 3 4 5
//5 4 3 2 1 2 3 4 5

Inputs & Outputs

ItemTypeDescription
knumberOuter (maximum) number — also sets row count and half-width.
inumberOuter loop — current row/layer value (k down to 1).
jnumberInner loop — column index for left (k..1) or right (2..k) half.
Widthnumber2 × k - 1 numbers per row (9 when k = 5).

Minimal workflow

JavaScript
for (let i = k; i >= 1; i--) {
  let line = "";
  for (let j = k; j >= 1; j--)        // left half
    line += (j > i ? j : i) + " ";
  for (let j = 2; j <= k; j++)        // right half
    line += (j > i ? j : i) + " ";
  console.log(line);
}

Approach comparison

ApproachIdeaBest for
Two inner loops + if5 4 3 2 1 2 3 4 5 bottom rowLearning and interviews
User-input kparseInt(prompt())Flexible outer value
Ternary operatorj > i ? j : iCompact one-liner per cell

⚡ Quick Reference

GoalPattern
Walk layersfor (let i = k; i >= 1; i--)
Left halffor (let j = k; j >= 1; j--)
Right halffor (let j = 2; j <= k; j++)
Cell ruleline += (j > i ? j : i) + " "
Ternary formline += (j > i ? j : i) + " "
Row width2 × k - 1 numbers per row
Program 45 contrastStar-and-zero X on a fixed grid — not concentric numbers

📋 Fixed k vs User Input vs Ternary

Same concentric square — different ways to set k and write the cell rule.

Outer loop
i = k..1

Layers from outside in

Left half
j = k..1

Descending columns

Right half
j = 2..k

Mirror without center dup

Cell rule
j > i ? j : i

Outer or layer value

Context

When This Pattern Shows Up

Reach for this pattern when teaching symmetric output, layer logic, and dual inner loops.

  1. Post Program 45 exercise

    Natural follow-up after Program 45 — same nested loops but adds symmetric row building.

  2. Mirror-half practice

    Left and right inner loops teach symmetry without string reversal.

  3. Layer / peel logic

    j > i selects which concentric ring each cell belongs to.

  4. Gateway to variants

    Compare Program 45 (star/zero X) and Program 47 (next in series) 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, symmetry, and O(k²) thinking.

🔮 Live Preview

Choose outer value k between 3 and 7 and draw the concentric number square in the browser.

Try 3, 5, or 7. Max up to 7 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed k = 5, prompt() input, and compact k = 3 trace demo. Click View Output to reveal sample console results, or Try it Yourself to run the code live.

📚 Getting Started

Print a concentric number square with k = 5 using two inner loops and the j > i rule.

Example 1 — Fixed k = 5

Hard-coded outer value — ideal for first demos and screenshots.

JavaScript
const k = 5;

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

How It Works

When i = 5 (first row), every j satisfies j > i is false for the inner range — all cells print 5. When i = 1 (last row), the center prints 1 and outer columns print ascending/descending values.

📈 User Input

Read outer value k from the console instead of hard-coding 5.

Example 2 — User Input k

Read k with prompt() and reject non-positive values.

JavaScript
const kInput = prompt("Enter k:");
const k = parseInt(kInput, 10);

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

How It Works

Same inner-loop core as Example 1; only the source of k changes from a literal to user input. Width becomes 2k - 1 automatically.

⚡ Compact k = 3

Smaller outer value for quick tracing — same logic, fewer rows.

Example 3 — Compact k = 3

Use k = 3 to trace the pattern quickly on paper or in interviews.

JavaScript
const k = 3;

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

How It Works

Only three rows — easy to dry-run each j value. The ternary j > i ? j : i replaces the if-else from Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed. Set k = 5 as the outer value and row/layer count.

Setup
2

Outer loop controls layer

for (let i = k; i >= 1; i--) walks concentric layers from k down to 1.

Grid
3

Left half (j = k..1)

If j > i append j; else append i — builds descending left side.

Condition
4

Right half mirrors (j = 2..k)

Same rule for j = 2..k — mirrors the left half without duplicating the center.

Output
5

New line

console.log(line) ends each row after both inner loops finish.

Break
=

Concentric square complete

k rows × 2k - 1 columns — O(k²) time, O(1) extra memory.

🔎 Worked Walkthrough — row i = 3, k = 5

Trace left-half columns j on row 3 — which value prints for each cell.

jj > i?Prints
5Yes5
4Yes4
3No3 (i)
2No3 (i)
1No3 (i)

Left half of row 3: 5 4 3 3 3. Right half (j = 2..5) mirrors to 3 3 4 5 — full row: 5 4 3 3 3 3 3 4 5. Total cells per row = 2k - 1 = 9.

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 k to 3 for a quick trace — see Example 3.

2. Pattern Series Base

Foundation for concentric layers, symmetric grids, and peel-down patterns.

Example: continue to Program 47 for the next pattern in the series.

3. Console Formatting Drills

Practice building a line string vs calling console.log() without complex math.

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

4. Symmetry Practice

Two inner loops teach left-right mirroring without string reversal.

Example: trace row i = 3 in the walkthrough table.

5. Complexity Intuition

k rows × 2k - 1 columns makes O(k²) concrete.

Example: count cells for k = 5 — 5 rows × 9 cols = 45 prints.

6. Input Validation Labs

Pair the pattern with Number.isFinite() 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.

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

    Change k, use ternary form, or trace with k = 3 for quick dry-runs.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace row i = 3 on paper — watch how j > i switches from outer values to the current layer.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Use the k Variable

    Never hard-code 5 in loop bounds — use k everywhere.

  2. 2. Validate with Number.isFinite()

    Avoid crashes when the user types letters instead of a number for k.

  3. 3. Keep Newline Outside

    Only call console.log(line) after both inner loops finish the row.

  4. 4. Two Inner Loops

    Left half uses j = k..1; right half uses j = 2..k — do not repeat j = 1 on the right.

  5. 5. Dry-Run k = 3

    Trace all three rows on paper before coding the full k = 5 demo.

Pro Tip: if the output is a vertical list of single numbers per line, you almost certainly put console.log() inside the inner loop.

Common Pitfalls

Mistakes that commonly break concentric number square patterns.

  1. 1. Newline Inside the Inner Loop

    Each cell lands on its own line — you get a column, not a square.

    → Use line += (j > i ? j : i) + " " per cell; console.log(line) only after both inner loops.

  2. 2. Right Loop Starts at 2

    Starting the right half at j = 1 duplicates the center digit on every row.

    → Use for (let j = 2; j <= k; j++) for the mirror half.

  3. 3. Reversed Outer Loop

    Using i = 1..k prints the pattern upside-down — center row appears first.

    → Use for (let i = k; i >= 1; i--) to start from the outer layer.

  4. 4. k Too Small

    k = 1 prints a single 1; k = 2 gives a minimal 3-column square.

    → Validate k >= 2 for interactive programs expecting a visible pattern.

  5. 5. Bare parseInt(prompt())

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

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

k = 1

Single cell

Output is just 1 on one line — no layers to peel.

k = 0

Empty pattern

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

Negative

k < 0

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

k = 2

Minimal square

Three columns wide — 2 2 2, 2 1 2.

Bad input

Non-numeric input

Bare parseInt(prompt()) returns NaN on bad input — use Number.isFinite() first.

Large rows

Large row count

Each row prints 2k - 1 cells — total work grows as .

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Star-and-zero X

  • Review Program 45’s star-and-zero X grid
  • Compare with Program 45

2. Change k

  • Try k = 4 or k = 6 — width becomes 2k - 1
  • Same nested loops, different outer value

3. Next in series

  • Continue with Program 47
  • Build on concentric layer logic

4. Ternary form

  • Use j > i ? j : i instead of if-else
  • Same logic, compact one-liner — see Example 2

Notes

  • Cell rule. Append j when j > i; otherwise append i. Apply in both left and right inner loops.
  • Build each row in a line string; call console.log(line) only after both inner loops finish.
  • Validate k > 0 for interactive programs; k = 1 prints a single 1.
  • k rows × 2k - 1 columns per row — total prints ≈ k × (2k - 1).

Quick Takeaway: outer loop i = k..1, two inner loops, append j if j > i else i, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(k²)O(1)
Smaller demo (Example 3)O(k²)O(1)
Wrap Up

🎉 Conclusion

The concentric number square is a compact nested-loop lesson: peel layers from k down to 1 using the j > i rule on left and right halves. Master the fixed-k version, then try user input and the compact k = 3 trace.

Practice the three examples above, then continue to Program 47 for the next pattern in the series.

Left half j = k..1, right half j = 2..k — same cell rule in both loops and validate k when reading input.

💡 Best Practices

✅ Do

  • Use for (let i = k; i >= 1; i--)
  • Left: for (let j = k; j >= 1; j--), Right: for (let j = 2; j <= k; j++)
  • Append j if j > i, else i to line
  • Validate k ≥ 1 for interactive programs
  • Check Number.isFinite(k) after parseInt(prompt())

❌ Don’t

  • Call console.log() inside the inner cell loop
  • Start the right loop at j = 1 — duplicates center
  • Use i = 1..k — prints pattern upside-down
  • Ignore bad console input in user-facing demos
  • Skip the k = 3 dry-run before coding k = 5

Key Takeaways

Knowledge Unlocked

Five things to remember about this concentric number square

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Layers i = k..1

Code
03

Two inners

Left k..1, right 2..k

Code
04

Symmetry

Mirror halves

Logic
O 05

Complexity

O(k²) time

Analysis

❓ Frequently Asked Questions

A concentric number square where the outer layer is k (e.g. 5) and numbers decrease toward the center, ending with 1, then mirror back out symmetrically.
Each row appends a left half (j = k..1) and a right half (j = 2..k) with the same j > i rule, mirroring values around the center.
When column j is still outside the current row layer i, append j (the outer number). Otherwise append i (the current row value).
The first loop builds the left descending half; the second loop mirrors columns 2..k on the right without repeating the center digit.
Change k (or read it from prompt()). Total width becomes 2*k - 1 — see Example 2.
O(k²) because each row appends roughly 2k - 1 cells and there are k rows.
Program 45 prints a star-and-zero X on a fixed grid. Program 46 prints decreasing/increasing numbers in a concentric square.
Each row has 2*k - 1 numbers. For k = 5, width is 9 columns.
Yes — line += (j > i ? j : i) + " " replaces the if-else in one expression — see Example 3.
Use parseInt with Number.isFinite and validate k > 0 before printing.

Did you Know? 🔊

Each cell appends j when j > i, else i. Row i runs from k down to 1; grid width = 2k - 1 columns per row.

Continue to Program 47

Move on to the next pattern in the JavaScript number-pattern series.

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