Increasing-Decreasing Number Pyramid in JavaScript

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

What You’ll Learn

Program 52 prints an increasing-decreasing number pyramid: each row is palindromic — count up from i to the peak, then back down — a natural step after Program 51’s alternating number triangle. This tutorial covers two inner loops per row, peak step-back with m -= 2, a live preview, worked JavaScript examples, edge cases, and complexity.

Shape Rule

Palindromic row

Row i prints i..(2i-1) ascending, then back down to i — always 2i-1 digits.

Outer Loop

i = 1..rows

for (let i = 1; i <= rows; i++) sets m = i as the starting number each row.

Increasing Half

j = 1..i

for (let j = 0; j < i; j++) { line += m; m++; } appends up to the peak.

Peak Step-Back

m -= 2

Step back before the decreasing loop so the peak digit is not printed twice.

Decreasing Half

k = 1..(i-1)

for (let k = 0; k < i - 1; k++) { line += m; m--; } mirrors the ascending half.

O(n²)

Complexity

Total prints = 1+3+5+…+(2n-1) = n² — each row grows by 2 digits.

Introduction

An increasing-decreasing number pyramid pattern prints row i as a palindrome — count up from i to the peak 2i-1, then back down to i. With rows = 5, you get 1, 232, 34543, 4567654, 567898765.

In JavaScript, set m = i each row, append the increasing half with m++, step back with m -= 2, then append the decreasing half with m-- before console.log(line).

Why it matters?

It bridges Program 51’s alternating triangle to palindromic rows — combining two inner loops with a peak step-back trick.

Key Highlights

Increasing half

m starts at i; print i times with m += 1.

Peak step-back

m -= 2 skips repeating the peak digit.

vs Program 51

Program 51 uses a continuous counter; Program 52 resets m = i and builds a palindromic row.

Series Foundation

Follow Program 51; continue to Program 53 next.

In short: set m = i, append increasing with m++, step back m -= 2, append decreasing with m--, then console.log(line).

📝 Problem & Approach

Given row count rows = 5, print an increasing-decreasing number pyramid — row i shows a palindromic sequence from i up to 2i-1 and back.

JavaScript
// rows = 5
// 1
// 232
// 34543
// 4567654
// 567898765

Inputs & Outputs

ItemTypeDescription
rowsnumberHow many triangle rows to print.
i (outer)numberCurrent row index — runs from 1 to rows.
mnumberCurrent print value — starts at i each row; incremented then decremented.
j (increasing)numberPrints i ascending digits with m += 1.
k (decreasing)numberPrints i-1 descending digits with m -= 1 after m -= 2.
Row lengthnumberRow i prints exactly 2i-1 digits.

Minimal workflow

JavaScript
for (let i = 1; i <= rows; i++) {
  let m = i;
  let line = "";
  for (let j = 0; j < i; j++) { line += m; m++; }
  m -= 2;
  for (let k = 0; k < i - 1; k++) { line += m; m--; }
  console.log(line);
}

Approach comparison

ApproachIdeaBest for
Two inner loopsIncreasing m += 1, then decreasing m -= 1 after m -= 2Learning and interviews
Peak step-backm -= 2 skips repeating the peak digitPalindromic row construction
User-input rowsparseInt(prompt())Flexible row count
Compact tracerows = 3 on paper firstQuick dry-runs before full demo
Spaced variantline += m + " "Easier reading per row

⚡ Quick Reference

GoalPattern
Outer loopfor (let i = 1; i <= rows; i++)
Init m per rowlet m = i;
Increasing halffor (let j = 0; j < i; j++) { line += m; m++; }
Peak step-backm -= 2
Decreasing halffor (let k = 0; k < i - 1; k++) { line += m; m--; }
End rowconsole.log(line);
Program 51 contrastProgram 51 uses a continuous counter; Program 52 builds palindromic rows with m = i

📋 Fixed Rows vs User Input vs Compact Trace

Same triangle — three ways to set row count and format output.

Fixed rows
rows = 5

Hard-coded height for demos

User input
parseInt(prompt())

Read row count from console

Compact trace
rows = 3

Quick dry-run on paper

Peak step-back
m -= 2

Skip repeating the peak digit

Palindrome
2i - 1

Digits per row i

Context

When This Pattern Shows Up

Reach for this pattern when teaching palindromic sequences, two inner loops per row, and the peak step-back trick.

  1. Post Program 51 exercise

    Natural follow-up after Program 51’s alternating triangle — introduces palindromic rows per line.

  2. Palindrome drills

    Each row reads symmetrically — good bridge to string palindrome problems.

  3. Two halves per row

    Total prints = 1+3+5+…+(2n-1) = n² — classic nested-loop complexity.

  4. Gateway to variants

    Compare Program 51 (alternating triangle) with this palindromic pyramid, then continue to Program 53.

  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 palindromic rows, peak step-back, and O(n²) thinking.

🔮 Live Preview

Choose row count between 3 and 9 and draw the increasing-decreasing number pyramid in the browser.

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

Live result
Press "Draw pattern".

Examples Gallery

Three complete JavaScript programs — fixed rows, user input, and a compact trace demo. Click View Output to reveal sample console results, or Try it Yourself to run in the browser.

📚 Getting Started

Print five rows of the palindromic number pyramid with increasing then decreasing halves per row.

Example 1 — Fixed rows = 5

Hard-coded row count — print ascending with m += 1, step back with m -= 2, then print descending with m -= 1.

JavaScript
const rows = 5;

for (let i = 1; i <= rows; i++) {
  let m = i;
  let line = "";

  for (let j = 0; j < i; j++) {
    line += m;
    m++;
  }

  m -= 2;

  for (let k = 0; k < i - 1; k++) {
    line += m;
    m--;
  }

  console.log(line);
}
Try it Yourself

How It Works

When i = 3, m prints 345, then m -= 2 gives 3, and the second loop prints 43 — output 34543. When i = 1, only the increasing loop runs and the decreasing loop is skipped.

📈 User Input

Read row count with prompt() and Number.isFinite validation.

Example 2 — User Input Rows

Read rows with prompt() and validate the result.

JavaScript
const rowsInput = prompt("Enter the number of rows:");
const rows = parseInt(rowsInput, 10);

if (!Number.isFinite(rows) || rows < 1) {
  console.log("Please enter a positive integer.");
} else {
  for (let i = 1; i <= rows; i++) {
    let m = i;
    let line = "";

    for (let j = 0; j < i; j++) {
      line += m;
      m++;
    }

    m -= 2;

    for (let k = 0; k < i - 1; k++) {
      line += m;
      m--;
    }

    console.log(line);
  }
}
Try it Yourself

How It Works

Same palindromic two-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Compact Trace

Smaller row count for quick tracing on paper or in interviews.

Example 3 — Compact rows = 3

Use rows = 3 to trace the increasing half, peak step-back, and decreasing half before scaling to 5 rows.

JavaScript
const rows = 3;

for (let i = 1; i <= rows; i++) {
  let m = i;
  let line = "";

  for (let j = 0; j < i; j++) {
    line += m;
    m++;
  }

  m -= 2;

  for (let k = 0; k < i - 1; k++) {
    line += m;
    m--;
  }

  console.log(line);
}
Try it Yourself

How It Works

With only three rows you can trace every m += 1 and m -= 1 step on paper before running the full rows = 5 demo.

🧠 How the Algorithm Prints Rows

1

Set m = i each row

Before each row, m = i — the starting digit for the palindromic sequence.

Setup
2

Print increasing half

for (let j = 0; j < i; j++) { line += m; m++; } — counts up to the peak.

Increase
3

Step back from peak

m -= 2 — avoids printing the peak digit twice in the decreasing half.

Peak
4

Print decreasing half

for (let k = 0; k < i - 1; k++) { line += m; m--; } then console.log(line).

Decrease
=

Palindromic pyramid complete

Total prints = 1+3+5+…+(2n-1) = n²O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each row’s increasing half, peak step-back, decreasing half, and full line output.

iPeakIncreasingAfter m-2DecreasingRow output
111(skip)(skip)1
232322232
3534534334543
47456756544567654
595678978765567898765

Row i always prints exactly 2i-1 digits — a palindromic line built from two inner loops.

Use Cases

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

1. Teaching Nested Loops

Inner bound grows with outer index — classic nested-loop exercise.

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

2. Palindrome Drills

Each row reads symmetrically — good bridge to string palindrome problems.

Example: row 5 ends with 567898765 — nine digits on a palindromic line.

3. Output Formatting Drills

Practice line += m vs console.log(line) with two inner loops per row.

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

4. Palindromic Row Math

Total logs = 1+3+5+…+(2n-1) = n² — odd-count summation per row.

Example: 10 rows log 100 digits total.

5. Complexity Intuition

Growing inner bound makes O(n²) concrete — count prints for n rows.

Example: 5 rows = 1+3+5+7+9 = 25 digit logs.

6. Input Validation Labs

Pair the pattern with Number.isFinite and positive-row checks after parseInt(prompt()).

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain 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 C courses.

  1. 1. Instant Visual Feedback

    Wrong inner bounds show up immediately as a broken triangle.

  2. 2. Real Math Connection

    Each row is a palindromic sequence — not abstract loop drill.

  3. 3. Easy to Extend

    Change rows, use fixed-width format, or switch to full rectangular table.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace row i = 3 on paper — watch m print 345, step back to 3, then print 43.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Inner bound = i

    Row i logs exactly 2i - 1 digits — use for (let j = 0; j < i; j++) then for (let k = 0; k < i - 1; k++).

  2. 2. Validate with Number.isFinite

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

  3. 3. console.log After Inner Loop

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

  4. 4. Fixed-Width Formatting

    Trace rows = 3 on paper before coding the full rows = 5 demo.

  5. 5. Dry-Run rows = 5

    Trace five rows on paper before coding the full 10-row demo.

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

Common Pitfalls

Mistakes that commonly break increasing-decreasing number pyramid patterns.

  1. 1. console.log Inside Inner Loop

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

    → Use line += m in both loops; console.log(line) only after both inner loops.

  2. 2. Wrong Inner Bound

    Using j < rows every row makes a full rectangle, not a palindromic pyramid row.

    → Use for (let j = 0; j < i; j++) — inner bound depends on outer i.

  3. 3. Forgetting m -= 2

    The peak digit prints twice — row looks like 2332 instead of 232.

    → Always step back with m -= 2 before the decreasing loop.

  4. 4. Forgetting console.log After Row

    All numbers print on one long line without row breaks.

    → Add console.log(line) after both inner loops complete.

  5. 5. Bare parseInt(prompt())

    Letters or empty input yield NaN when parseInt(prompt()) is unchecked.

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

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 on one line.

rows = 0

Empty output

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

Negative

rows < 0

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

rows = 5

Compact trace

Five rows ending with 567898765 — good for dry-runs.

Bad input

Non-numeric input

Unchecked parseInt(prompt()) returns NaN — validate with Number.isFinite.

Large rows

Wide output

Row 9 has 17 digits — total logs grow as .

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Compare with Program 51

  • Program 51 uses a continuous counter with alternating direction
  • Program 52 resets m = i and builds palindromic rows

2. Change rows

  • Try rows = 4 or rows = 8 in the live preview
  • Same palindromic logic, different pyramid size

3. Next in series

  • Continue with Program 53
  • Build on palindromic number patterns

4. Add spacing

  • Append with line += m + " "
  • Same loops, wider visual spacing

Notes

  • Two inner loops. Set m = i. Increasing: for (let j = 0; j < i; j++) with m++. Decreasing: for (let k = 0; k < i - 1; k++) with m-- after m -= 2.
  • line += m builds the row; console.log(line) advances — call it only after both inner loops finish.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single 1.
  • Total prints = 1+3+5+…+(2n-1) = n² for n rows — each row has 2i-1 digits.

Quick Takeaway: set m = i, append increasing with m++, step back m -= 2, append decreasing with m--, then console.log(line).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Total digit logs for n rowsO(1)
Wrap Up

🎉 Conclusion

The increasing-decreasing number pyramid is a natural follow-up to Program 51: palindromic rows built with two inner loops and a peak step-back. Master the fixed-rows version, then try user input and the compact 3-row trace.

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

Row i prints 2i-1 palindromic digits — ascending to the peak, then back down.

💡 Best Practices

✅ Do

  • Set int m = i at the start of each row
  • Increasing: for (let j = 0; j < i; j++) { line += m; m++; }
  • Peak step-back: m -= 2
  • Decreasing: for (let k = 0; k < i - 1; k++) { line += m; m--; }
  • Call console.log(line) after both inner loops

❌ Don’t

  • Skip m -= 2 — the peak prints twice
  • Use j < i in the decreasing loop when you meant k < i - 1
  • Call console.log(line) inside either inner loop
  • Ignore bad input in user-facing demos
  • Skip the rows = 3 dry-run before coding rows = 5

Key Takeaways

Knowledge Unlocked

Five things to remember about this increasing-decreasing number pyramid

Print the pattern the beginner-friendly way.

5
Core concepts
02

Start m

m = i each row

Code
03

Peak step

m -= 2

Code
04

Row length

2i - 1 digits

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Row 3 starts at 3, appends up to 5 (345), then appends back down to 3 (43) after m -= 2 — producing 34543.
Each row counts up from i to the peak 2i-1, then counts back down to i. The sequence reads the same left-to-right on each line.
After the increasing loop, m is one past the peak. Subtracting 2 moves it to the value just before the peak so the decreasing loop does not repeat the peak digit.
Step back with m -= 2 before the decreasing loop. The decreasing loop then runs i-1 times, skipping the peak.
Change rows or read it from user input with parseInt(prompt()) — see Example 2.
O(n²) for n rows because row i logs 2i-1 digits and 1+3+5+...+(2n-1) = n² total logs.
Program 51 uses a continuous counter with alternating direction across rows. Program 52 resets m = i each row and builds a palindromic line per row.
Yes. Use line += m + " " in both loops and trim before console.log if needed.
Use parseInt with Number.isFinite. Bare parseInt(prompt()) returns NaN on bad input.
One row logs 1 — the decreasing loop never runs when i = 1.

Did you Know? 🔊

Each row is palindromic: append i..(2i-1) ascending, then back down with m -= 2 to skip the peak. Row 3 logs 34543 — total digits = 1+3+5+…+(2n-1) = n² for n rows.

Continue to Program 53

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

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