Palindromic Number Pyramid Number Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Increase + Decrease

What You’ll Learn

The palindromic number pyramid prints centered rows that read the same forwards and backwards. For rows = 5: 1, 1 2 1, 1 2 3 2 1, and so on. Each row uses leading spaces, an increase loop 1..i, and a decrease loop i-1..1. This tutorial covers the three-part row logic, live preview, worked Java examples, edge cases, and O(n²) complexity.

Leading Spaces

j = rows..i

Print rows - i + 1 pairs of spaces to center each row.

Increase Loop

k = 1..i

Print numbers 1 through i on the way up.

Decrease Loop

--n

Set n = i, then print --n for i-1 steps — mirrors without duplicating peak.

Palindromic Row

2i - 1 nums

Row i has 2i-1 numbers — increase half plus decrease half.

Live Preview

3–12 rows

Pick row count and draw the palindromic pyramid instantly in the browser.

O(n²)

Complexity

Each row prints O(n) spaces and numbers — total work grows as n².

Introduction

A palindromic number pyramid centers each row with leading spaces, then prints 1..i and i-1..1. Row 2 reads 1 2 1; row 3 reads 1 2 3 2 1.

In Java: outer for (i = 1; i <= rows; i++), space loop j = rows..i, increase loop k = 1..i, decrease loop with --n, then println().

📝 Problem & Approach

Given rows = 5, print five centered palindromic rows — widest row has 1 2 3 4 5 4 3 2 1.

Java
// rows = 5 (conceptual output — centered)
//         1 
//       1 2 1 
//     1 2 3 2 1 
//   1 2 3 4 3 2 1 
// 1 2 3 4 5 4 3 2 1 

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle rows (typically ≥ 1).
i, j, k, n, mintRow i; space index j; increase k; decrease n/m.
Printed outputtext2i-1 numbers per row when centered; palindromic sequence.

Minimal workflow

Pseudocode
for i from 1 to rows:
    print (rows-i+1) space pairs
    print 1..i
    print i-1..1 using --n
    newline

Approach comparison

ApproachIdeaBest for
Three-part rowSpaces + increase loop + decrease loopCentered palindromic rows
StringBuilder rowBuild row without trailing spacesCleaner console output — Example 3
Scanner inputsc.nextInt() for rowsUser-chosen row count
Compact outputStringBuilder joins values with single spacesNo trailing space per row — Example 3

⚡ Quick Reference

GoalPattern
Set rowsint rows = 5;
Outer loopfor (i = 1; i <= rows; i++)
Space loopfor (j = rows; j >= i; j--) print(" ")
Increase loopfor (k = 1; k <= i; k++) print(k)
Decrease loopn = i; print(--n) for m = 1..i-1
Row breakSystem.out.println(); after all three parts
Program 55 contrastDiagonal-fill triangle uses step logic; this pyramid uses centered palindrome rows

📋 Spaces vs Increase vs Decrease

How leading spaces, increase loop, decrease loop, and row breaks work together.

Leading spaces
for (j = rows; j >= i; j--)
  print("  ")

Centers row i in the pyramid.

Increase loop
for (k = 1; k <= i; k++)
  print(k)

Prints 1 2 3 ... i on row i.

Decrease loop
n = i
for (m = 1; m < i; m++)
  print(--n)

Prints i-1 ... 1 — mirrors without repeating peak.

Learning tip
trace i=3, rows=5

Dry-run row 3: spaces + 1 2 3 + 2 1 → palindrome.

Context

When This Pattern Shows Up

Reach for this pattern when teaching centering, palindrome rows, and nested loops.

  1. First lab exercise

    Classic follow-up after diagonal-fill triangles — introduces centered palindromic rows.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible pattern size.

  4. Gateway to variants

    Compare with Program 55 (diagonal-fill triangle), then continue to Program 57 hollow pyramid.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one program that locks in centering, palindrome rows, and O(n²) thinking.

🔮 Live Preview

Choose pattern size n and draw the full palindromic number pyramid number pattern in the browser.

Try 3, 5, or 8 for rows (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed rows = 5, Scanner input, and a compact StringBuilder variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five centered palindromic rows — widest row has nine numbers.

Example 1 — Fixed rows = 5

Hard-coded rows = 5 — leading spaces, increase loop 1..i, decrease loop with --n.

Java
public class PalindromicNumberPyramid {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = rows; j >= i; j--) System.out.print("  ");
            for (int k = 1; k <= i; k++) System.out.print(k + " ");

            int n = i;
            for (int m = 1; m < i; m++) System.out.print(--n + " ");

            System.out.println();
        }
    }
}

How It Works

Row 1 prints one centered 1. Row 3 prints spaces, then 1 2 3, then 2 1 — a palindrome.

📈 Practical Variant

Read rows with Scanner for flexible output size.

Example 2 — Scanner Input

Same palindromic row logic; row count comes from user input.

Java
import java.util.Scanner;

public class PalindromicNumberPyramidInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter rows: ");
        int rows = sc.nextInt();

        for (int i = 1; i <= rows; i++) {
            for (int j = rows; j >= i; j--) System.out.print("  ");
            for (int k = 1; k <= i; k++) System.out.print(k + " ");
            int n = i;
            for (int m = 1; m < i; m++) System.out.print(--n + " ");
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same palindromic row logic as Example 1; row count comes from Scanner input.

⚡ Compact Variant

Build each row with StringBuilder — no trailing space.

Example 3 — Compact Rows

Same logic; use StringBuilder to join values without a trailing space.

Java
public class PalindromicNumberPyramidCompact {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            StringBuilder row = new StringBuilder();
            for (int j = rows; j >= i; j--) row.append("  ");
            for (int k = 1; k <= i; k++) {
                if (row.length() > 0 && !row.toString().endsWith("  ")) row.append(" ");
                row.append(k);
            }
            int n = i;
            for (int m = 1; m < i; m++) {
                row.append(" ").append(--n);
            }
            System.out.println(row);
        }
    }
}

How It Works

Same palindromic logic; StringBuilder produces clean rows without trailing spaces.

🧠 How the Algorithm Builds Each Row

1

Set up & outer loop

Set rows (e.g. 5). Outer loop for (i = 1; i <= rows; i++) builds one centered row per iteration.

Setup
2

Print leading spaces

for (j = rows; j >= i; j--) prints " " to center row i.

Spaces
3

Print increasing half

for (k = 1; k <= i; k++) prints 1 2 3 ... i.

Increase
4

Print decreasing half

n = i, then print(--n) for m = 1..i-1; then println().

Break
=

Palindromic number pyramid complete

Total numbers = (e.g. 25 for rows=5) — O(n²) time, O(1) extra memory.

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

Trace row 3 to see spaces, increase half, and decrease half form 1 2 3 2 1.

PhaseLoopRow so far
Spacesj=5..3    
Increasek=1..3    1 2 3
Decreasem=1,2 → --n    1 2 3 2 1

Final centered row 3: 1 2 3 2 1. Then println() moves to row 4.

Use Cases

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

1. Teaching Increase + Decrease

Clearest visual proof that outer and inner bounds interact.

Example: use Scanner for dynamic rows — see Example 2.

2. Leading Space Padding

Each row prints rows - i + 1 pairs of spaces before numbers.

Example: trace row 3 with rows=5 — 2 space pairs before digits.

3. Console Formatting Drills

Practice println vs print for multi-line vs single-line output.

Example: use StringBuilder for clean rows — see Example 3.

4. Palindrome Check

Each row reads the same forwards and backwards — peak digit appears once.

Example: row 4 reads 1 2 3 4 3 2 1 when centered.

5. Complexity Intuition

Each row prints O(n) spaces and numbers — total work grows as n².

Example: count numbers on row 5 → 2×5-1 = 9 digits per row.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

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

Pro Tip: when an interviewer asks for patterns, explain the outer/inner loop roles first — then write the loops. The story matters as much as the code.

Advantages

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

  1. 1. Instant Visual Feedback

    Missing decrease loop shows immediately — rows are not palindromic.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Change rows, use Scanner, or build rows with StringBuilder.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the three-part row (spaces, up, down) first; then try Scanner input and the StringBuilder variant in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Variables Clearly

    Use rows for height and i/j/k/res for loop variables.

  2. 2. Prefer Scanner

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

  3. 3. Row Break After Inner Loop

    Finish the inner loop for row i, then call println().

  4. 4. Use --n for Decrease

    Set n = i before the decrease loop; print --n exactly i-1 times.

  5. 5. Dry-Run One Small Row Count

    Trace rows = 5, i = 3 on paper — expect centered 1 2 3 2 1.

Pro Tip: if the peak digit prints twice, check whether the decrease loop uses m < i.

Common Pitfalls

Mistakes that commonly break palindromic number pyramid number patterns.

  1. 1. println() Inside an Inner Loop

    Each number lands on its own line — you get a vertical stack, not a centered pyramid row.

    → Use print inside space, increase, and decrease loops; println() only after they finish.

  2. 2. Forgetting the Decrease Loop

    Without --n, rows print only 1..i — no palindrome.

    → Add the decrease loop: n = i, then print(--n) for m = 1..i-1.

  3. 3. Forgetting the Row Break

    Omitting println() after both inner loops glues all rows onto one line.

    → Always call System.out.println() after space, increase, and decrease loops complete.

  4. 4. Decrease Loop Uses i Instead of i-1

    Looping m = 1..i duplicates the peak digit — row 3 becomes 1 2 3 3 2 1.

    → Use m < i so exactly i-1 descending digits print.

  5. 5. Unchecked Scanner Input

    Letters or empty input throw InputMismatchException.

    → Use sc.hasNextInt() before sc.nextInt().

  6. 6. Hard-coding 5 Everywhere

    Using literal 5 in loop bounds instead of variable n breaks dynamic input.

    → Use one rows variable for outer loop and k initialization.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single line

Output is one line: 1 — bottom half loop does not run.

rows = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

rows < 0

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

Large rows

Large rows

Large values produce wide rows — fine for labs; use smaller n for quick demos.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves rows unset — call sc.hasNextInt() first.

Compact

Single-line form

Use conditional spacing to avoid trailing spaces — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change n

  • Try n = 3, 6, or 8
  • Verify row i reads the same forwards and backwards

2. StringBuilder rows

  • Build each row without trailing spaces
  • Compare print-based vs StringBuilder output

3. Skip decrease loop

  • Omit the --n loop and see non-palindromic rows
  • Observe missing symmetry

4. Next in series

  • Continue with Program 57 hollow pyramid
  • Try rows=6 and verify row 6 reads 1 2 3 4 5 6 5 4 3 2 1

Notes

  • Cell count. Row i has 2i-1 numbers; total = (e.g. 25 numbers for rows=5).
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 prints one number.
  • Row logic: spaces, then 1..i, then --n for i-1 steps.

Quick Takeaway: outer i=1..rows; spaces; print 1..i; print --n; then println().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed rows = 5 (Example 1)O(n²)O(1)
Scanner input (Example 2)O(n²)O(1)
Compact rows (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The palindromic number pyramid combines centering with increase/decrease loops — a natural step after diagonal-fill triangle patterns. Master the fixed-rows version first, then try Scanner input and the compact StringBuilder variant in Example 3.

Practice the three examples above, then continue to Program 57 for the hollow number pyramid pattern.

Print leading spaces before numbers on every row — one println() per outer iteration.

💡 Best Practices

✅ Do

  • Explain outer i, space loop, increase loop, and decrease loop before coding
  • Print spaces, then 1..i, then --n; then println()
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Forget the decrease loop
  • Use m <= i in decrease loop (duplicates peak)
  • Hard-code 5 instead of variable rows
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this palindromic number pyramid pattern

Center each row with spaces, then print increase and decrease halves.

5
Core concepts
02

Outer loop

i = 1..rows

Code
03

Palindromic halves

Print 1..i then --n

Logic
n 04

Row length

2i-1 nums/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

Each row reads the same forwards and backwards — e.g. 1 2 3 2 1. Leading spaces center the pyramid shape.
Row 2 prints increasing 1 2, then decreasing 1 using the --n loop — forming a palindrome.
One loop prints 1..i, another prints i-1..1 with --n. Together they mirror the row without duplicating the peak.
Yes. Use a variable rows in all loop bounds and space padding.
2i - 1 numbers — i ascending plus i-1 descending.
Build each row with StringBuilder — see Example 3.
O(n²) for n rows because each row prints O(n) spaces and numbers.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Each row is palindromic: print leading spaces, numbers 1..i, then i-1..1. Row 3 reads 1 2 3 2 1 when centered.

Continue to Program 57

Move on to the hollow number pyramid pattern in the Java number-pattern series.

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