Hollow Number Pyramid Number Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Left + Right Edges

What You’ll Learn

The hollow number pyramid prints each row number at the left and right edges only — spaces fill the middle. For n = 5: 1, 2 2, 3 3, and so on. Each row uses a left loop j = n..1 and a right loop k = 2..n with i == j / i == k conditions. This tutorial covers edge-printing logic, live preview, worked Java examples, edge cases, and O(n²) complexity.

Left Edge Loop

j = n..1

Scan j from n down to 1; print i when i == j, else a space.

Right Edge Loop

k = 2..n

Scan k from 2 to n; print i when i == k, else a space.

Hollow Middle

spaces only

Every position that is not an edge prints a space — that creates the hollow look.

Two Edge Digits

2n-1 cols

Row i spans 2n-1 columns — row number at left and right edges (row 1 overlaps).

Live Preview

3–12 rows

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

O(n²)

Complexity

Each row scans O(n) positions — total work grows as n².

Introduction

A hollow number pyramid prints the row number at both pyramid edges and spaces everywhere else. Row 2 reads 2 2; row 3 reads 3 3 when aligned.

In Java: outer for (i = 1; i <= n; i++), left loop j = n..1 with i == j, right loop k = 2..n with i == k, then println().

📝 Problem & Approach

Given n = 5, print five hollow rows — widest row has 5 at both ends.

Java
// n = 5 (conceptual output)
//     1
//    2 2
//   3   3
//  4     4
// 5       5

Inputs & Outputs

ItemTypeDescription
nintPyramid height — number of rows (typically ≥ 1).
i, j, kintRow i; left index j; right index k.
Printed outputtext2n-1 columns per row; row number at left and right edges only.

Minimal workflow

Pseudocode
for i from 1 to n:
    for j from n down to 1: print i if i==j else space
    for k from 2 to n: print i if i==k else space
    newline

Approach comparison

ApproachIdeaBest for
Two-loop rowLeft edge loop + right edge loopHollow edge-only rows
StringBuilder rowBuild row without trailing spacesCleaner console output — Example 3
Scanner inputsc.nextInt() for nUser-chosen pyramid height
Compact outputStringBuilder joins values with single spacesNo trailing space per row — Example 3

⚡ Quick Reference

GoalPattern
Set nint n = 5;
Outer loopfor (i = 1; i <= n; i++)
Left loopfor (j = n; j >= 1; j--) print j if i==j else space
Right loopfor (k = 2; k <= n; k++) print k if i==k else space
Row breakSystem.out.println(); after both edge loops
Program 56 contrastPalindromic pyramid fills every row; this pattern prints edges only with spaces inside

📋 Left Edge vs Right Edge

How left edge loop, right edge loop, and row breaks work together.

Left edge
for (j = n; j >= 1; j--)
  print(i==j ? j : " ")

Right-aligns the left pyramid edge.

Right edge
for (k = 2; k <= n; k++)
  print(i==k ? k : " ")

Expands the right pyramid edge outward.

Learning tip
trace i=3, n=5

Dry-run row 3: left prints 3, right prints 3, middle is spaces.

Context

When This Pattern Shows Up

Reach for this pattern when teaching edge conditions, hollow shapes, and nested loops.

  1. First lab exercise

    Classic follow-up after palindromic pyramids — introduces hollow edge-printing.

  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 56 (palindromic pyramid), then continue to Program 58 hollow diamond.

  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 edge conditions, hollow rows, and O(n²) thinking.

🔮 Live Preview

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

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

Live result
Press "Draw pattern".

Examples Gallery

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

📚 Getting Started

Print five hollow rows — widest row shows 5 at both edges.

Example 1 — Fixed n = 5

Hard-coded n = 5 — left loop j = n..1, right loop k = 2..n, edge conditions i==j / i==k.

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

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

How It Works

Row 1 prints one 1 where edges overlap. Row 3 prints 3 at the left edge and 3 at the right — spaces fill the middle.

📈 Practical Variant

Read n with Scanner for flexible output size.

Example 2 — Scanner Input

Same hollow edge logic; pyramid height comes from user input.

Java
import java.util.Scanner;

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

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

        sc.close();
    }
}

How It Works

Same hollow edge logic as Example 1; height comes from Scanner input.

⚡ Compact Variant

Build each row with StringBuilder — same edge logic, cleaner assembly.

Example 3 — Compact Rows

Same edge logic; StringBuilder assembles left and right halves in one buffer.

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

        for (int i = 1; i <= n; i++) {
            StringBuilder row = new StringBuilder();
            for (int j = n; j >= 1; j--) row.append(i == j ? j : " ");
            for (int k = 2; k <= n; k++) row.append(i == k ? k : " ");
            System.out.println(row);
        }
    }
}

How It Works

Same edge logic; StringBuilder avoids repeated System.out.print calls per character.

🧠 How the Algorithm Builds Each Row

1

Set up & outer loop

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

Setup
2

Left edge loop

for (j = n; j >= 1; j--) prints i when i==j, else a space.

Left
3

Right edge loop

for (k = 2; k <= n; k++) prints i when i==k, else a space.

Right
4

Row break

System.out.println() after both edge loops finish — starts the next row.

Break
=

Hollow number pyramid complete

Each row scans 2n-1 positions (e.g. 9 columns when n=5) — O(n²) time, O(1) extra memory.

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

Trace row 3 to see left and right edge loops form 3 3.

PhaseLoopRow so far
Left edgej=5..1, i==3 at j=3  3 
Right edgek=2..5, i==3 at k=3  3   3 

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

Use Cases

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

1. Teaching Left + Right Edges

Clearest visual proof that outer and inner bounds interact.

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

2. Left/Right Split

Split each row into left half (j=n..1) and right half (k=2..n) for edge control.

Example: trace row 3 with n=5 — left prints 3 at column 3, right at column 5.

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. Hollow Shape

Only edge positions print digits — interior stays empty for the hollow effect.

Example: row 4 reads 4 4 — two fours at the edges.

5. Complexity Intuition

Each row scans O(n) positions — total work grows as n².

Example: count columns on row 5 → 2×5-1 = 9 character positions per row.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

Example: reject n <= 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 right edge loop shows immediately — only left digits appear.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Change n, use Scanner, mirror into a diamond (Program 58), or build rows with StringBuilder.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the two-loop row (left edge, right edge) 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 n for height and i/j/k 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. Start Right Loop at k = 2

    Starting at k = 1 duplicates the center on row 1 — use k = 2 to skip overlap.

  5. 5. Dry-Run One Small Row Count

    Trace n = 5, i = 3 on paper — expect 3 3 with spaces between edges.

Pro Tip: if row 1 shows two digits, check whether the right loop starts at k = 2.

Common Pitfalls

Mistakes that commonly break hollow number pyramid 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 left and right edge loops; println() only after they finish.

  2. 2. Forgetting the Right Edge Loop

    Without the k = 2..n loop, only the left edge prints — no right-side digit.

    → Add the right loop: for (k = 2; k <= n; k++) with i == k condition.

  3. 3. Forgetting the Row Break

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

    → Always call System.out.println() after left and right edge loops complete.

  4. 4. Right Loop Starts at k = 1

    Starting k = 1 duplicates the center on row 1 — use k = 2 instead.

    → Start the right half at k = 2 to skip the overlapping center column.

  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 n variable for outer loop and both inner loop bounds.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single line

Output is one line: 1 — right edge overlaps left on the single column.

n = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

n < 0

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

Large n

Large n

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

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves n 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 shows i at both edges

2. StringBuilder rows

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

3. Skip right loop

  • Omit the right loop and see only left-edge digits
  • Observe missing right edge

4. Next in series

  • Continue with Program 58 hollow diamond
  • Try n=6 and verify row 6 reads 6 at both ends with spaces between

Notes

  • Cell count. Each row spans 2n-1 columns; only two (or one on row 1) print digits.
  • print stays on the line; println advances — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 prints one digit where edges overlap.
  • Row logic: left loop j=n..1, then right loop k=2..n, edge conditions only.

Quick Takeaway: outer i=1..n; left loop j=n..1; right loop k=2..n; then println().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed n = 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 hollow number pyramid combines left/right edge loops with space padding — a natural step after the palindromic pyramid in Program 56. Master the fixed-n version first, then try Scanner input and the compact StringBuilder variant in Example 3.

Practice the three examples above, then continue to Program 58 for the hollow number diamond pattern.

Print edge digits only — spaces everywhere else — one println() per outer iteration.

💡 Best Practices

✅ Do

  • Explain outer i, left loop, and right loop before coding
  • Print left edge, then right edge; then println()
  • Validate n ≥ 1 for interactive programs
  • Check Scanner return value before using n
  • State O(n²) time when asked about complexity

❌ Don’t

  • Forget the right edge loop
  • Start right loop at k = 1 (duplicates center on row 1)
  • Hard-code 5 instead of variable n
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this hollow number pyramid pattern

Print row number at left and right edges; spaces fill the hollow middle.

5
Core concepts
02

Outer loop

i = 1..n

Code
03

Edge loops

Left j=n..1, right k=2..n

Logic
n 04

Row length

2n-1 cols/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

Row 2 places 2 at the left edge (when i==j) and again at the right edge (when i==k), with spaces between.
On row 1, the left and right edge conditions overlap at the same column — only one 1 appears.
Left loop j=n..1 prints i when i==j (right-aligned). Right loop k=2..n prints i when i==k (expanding outward).
Starting at 1 would duplicate the center column on row 1. k=2 skips the overlap.
Yes. Use a variable n in all loop bounds — the pyramid scales to n rows.
After rows 1..n, mirror rows n-1..1 with the same edge logic — see Program 58.
O(n²) because each row scans about 2n-1 positions to decide number or space.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Each row prints the row number at the left and right edges only — everything between is spaces. Row 1 overlaps at one position; row 5 reads 5 5.

Continue to Program 58

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

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