Center-Aligned Pyramid Star Pattern in Java

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2i - 1 stars

What You’ll Learn

A center-aligned pyramid combines leading spaces with odd star counts: (rows - i) spaces and (2 * i - 1) stars on row i. This tutorial covers the centering formula, why odd widths matter, a live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Peak on top

One star at the tip; each row adds one star on both sides.

Space Loop

rows - i

Same centering margin as Program 3 — shrinks as rows widen.

Odd Stars

2*i - 1

Print 1, 3, 5, … stars so the pyramid stays symmetric.

Base Width

2n - 1

Bottom row has 2 * rows - 1 stars and no leading spaces.

Live Preview

1–14 rows

Pick a height and draw the centered pyramid instantly.

O(n²)

n² stars

Sum of first n odd numbers is n² — O(n²) time, O(1) extra space.

Introduction

A center-aligned pyramid starts with a single * and widens by two stars each row, with leading spaces so the peak stays centered.

It extends Program 3’s spacing idea, but uses 2 * i - 1 stars instead of i. The same row body is the upper half of the filled diamond.

Why it matters?

Odd-width centering is the key skill behind pyramids, diamonds, and many hollow variants. Once 2*i-1 clicks, those patterns become small variations.

Key Highlights

Odd Widths

2*i - 1 keeps a single center column.

Leading Spaces

rows - i centers each star run.

Two Inner Loops

Spaces first, then the odd star run.

Diamond Building Block

Upper half of Program 10’s filled diamond.

In short: for each row i, print rows - i spaces, then 2 * i - 1 stars, then a newline.

📝 Problem & Approach

Given a positive integer rows, print a center-aligned full pyramid of * characters with rows lines.

Java
// First 5 rows (spaces shown as ·)
// ····*
// ···***
// ··*****
// ·*******
// *********

Inputs & Outputs

ItemTypeDescription
rowsintPyramid height (typically ≥ 1). Base width is 2 * rows - 1.
Printed outputtextCentered rows: (rows - i) spaces + (2 * i - 1) stars.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from 1 to (rows - i):
        print " "
    for k from 1 to (2 * i - 1):
        print "*"
    print newline

Approach comparison

ApproachIdeaBest for
Two nested loopsSpaces then odd star runLearning and interviews
"*".repeat() shortcutBuild padding and stars as stringsShorter demos after formulas click

⚡ Quick Reference

GoalPattern
Walk each rowfor (i = 1; i <= rows; i++)
Leading spacesfor (j = 1; j <= rows - i; j++) System.out.print(" ");
Odd star runfor (k = 1; k <= 2 * i - 1; k++) System.out.print("*");
Base width2 * rows - 1
Invert laterfor (i = rows; i >= 1; i--) (see Program 6)
String shortcutSystem.out.print(" ".repeat(rows - i)); System.out.println("*".repeat(2 * i - 1));

📋 Pyramid vs Triangle vs Diamond

Same space idea — star formula defines the shape.

Program 3
i stars

Right-aligned triangle — same spaces

This page
2*i - 1

Centered pyramid — odd star runs

Program 6
countdown i

Inverted pyramid — same inners

Program 10
+ mirror

Filled diamond — this page as upper half

Context

When This Pattern Shows Up

Reach for a centered pyramid when teaching odd-width growth after right-aligned triangles.

  1. After triangle labs

    Natural step once Programs 1–4 are solid.

  2. Odd-sequence practice

    2*i-1 is a classic loop bound interview warm-up.

  3. Diamond precursor

    Filled diamonds reuse this exact upper-half body.

  4. Symmetry teaching

    Fixed-pitch fonts make centering mistakes obvious.

  5. Not a UI layout tool

    Console teaching pattern — not how you build app screens.

Key benefit: one figure that locks in centering spaces and odd-width growth — the gateway to diamonds.

🔮 Live Preview

Choose a height between 1 and 14 and draw the centered pyramid in the browser.

Try 4, 5, or 7. Base width will be 2 * rows - 1.

Live result
Press "Draw pyramid".

Examples Gallery

Three complete Java programs — nested space/star loops, console input, and a "*".repeat() shortcut. Click View Output to reveal sample console results.

📚 Getting Started

Print a five-row centered pyramid with classic nested loops.

Example 1 — Fixed rows = 5

Space loop with rows - i, star loop with 2 * i - 1.

Java
public class CenterPyramid {
    public static void main(String[] args) {
        int rows = 5;
        int i, j, k;

        for (i = 1; i <= rows; i++) {
            for (j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

How It Works

When i = 1, print 4 spaces and 1 star. When i = 5, print 0 spaces and 9 stars (2*5-1). Each step adds one star on the left and one on the right of the previous run.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read rows with Scanner and nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class CenterPyramidInput {
    public static void main(String[] args) {
        int rows;
        int i, j, k;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of rows: ");
        rows = sc.nextInt();

        for (i = 1; i <= rows; i++) {
            for (j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

How It Works

Same space/star core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException — check hasNextInt() for safer labs.

⚡ Shortcut Style

Same pyramid without explicit character loops.

Example 3 — "*".repeat() for Spaces and Stars

Build each row’s margin and odd star run in one call each.

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

        for (int i = 1; i <= rows; i++) {
            System.out.print(" ".repeat(rows - i));
            System.out.println("*".repeat(2 * i - 1));
        }
    }
}

How It Works

Same formulas as Example 1; "*".repeat() replaces the two inner loops. Keep the nested-loop version for exams that want both bounds visible.

🧠 How the Algorithm Prints Rows

1

Set up

Set rows. Use i for the row, j for spaces, k for stars.

Setup
2

Outer loop

for (i = 1; i <= rows; i++) — tip when i == 1, base when i == rows.

Row
3

Centering spaces

for (j = 1; j <= rows - i; j++) System.out.print(" "); shrinks the margin as the row widens.

Center
4

Odd stars then newline

for (k = 1; k <= 2 * i - 1; k++) System.out.print("*"); then System.out.println().

Stars
=

Symmetric pyramid

Total stars ; O(n²) time, O(1) extra space. Base width 2n - 1.

🔎 Worked Walkthrough — rows = 4

Trace spaces, stars, and characters per row for each outer-loop value of i.

iSpaces rows - iStars 2*i - 1Chars before newlinePrinted row
1314   *
2235  ***
3156 *****
4077*******

Star total: 1+3+5+7 = 16 = 4². Tip rows are shorter than the base — unlike Program 3’s fixed width.

Use Cases

Where this pyramid (and odd-width centering) shows up beyond the homework prompt.

1. Teaching Odd Sequences

2*i-1 is a clear visual of the first n odd numbers.

Example: assert sum of stars equals rows * rows.

2. Diamond Upper Half

Reuse this body, then mirror from rows - 1.

Example: Program 10.

3. Invert Next

Countdown outer loop flips the pyramid.

Example: Program 6.

4. Compare With Program 3

Same spaces; swap i stars for 2*i-1.

Example: side-by-side for rows = 5.

5. Hollow Variants

Once solid works, print border stars only.

Example: stars on edges of each odd run.

6. Input Validation Labs

Pair with hasNextInt() and positive-row checks.

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

Pro Tip: say “rows - i spaces and 2*i-1 stars” before writing a single loop — that is the whole design.

Advantages

Why the centered pyramid is a favorite mid-series pattern.

  1. 1. Builds on Known Spacing

    Reuses Program 3’s margin; only the star formula is new.

  2. 2. Instant Symmetry Feedback

    Even widths or wrong spaces look “off” immediately.

  3. 3. Unlocks Diamonds

    Same row body powers filled and hollow diamond halves.

  4. 4. Nice Complexity Story

    Total stars = n² makes O(n²) concrete and memorable.

Pro Tip: master the nested-loop version first; treat "*".repeat() as a polish shortcut afterward.

Usage Tips

Small habits that keep pyramid code clean.

  1. 1. Keep 2 * i - 1

    2 * i (even) breaks the classic single-peak look.

  2. 2. Spaces Before Stars

    Always print the margin first — order matters for centering.

  3. 3. Check hasNextInt()

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

  4. 4. Use Real Spaces, Not Tabs

    Tabs break centering across fonts and editors.

  5. 5. Dry-Run One Small n

    Trace rows = 4 on paper before coding larger demos.

Pro Tip: if the shape leans like a right triangle, you almost certainly used i stars instead of 2*i-1.

Common Pitfalls

Mistakes that commonly break centered pyramids.

  1. 1. Using i Stars Instead of 2*i - 1

    You get a right-aligned triangle look, not a balanced pyramid.

    → Keep odd counts: 2 * i - 1.

  2. 2. Using 2 * i (Even Width)

    Even lengths lose the single center peak of the classic shape.

    → Prefer 2 * i - 1.

  3. 3. Off-by-One on Spaces

    j < rows - i instead of <= drops a needed space and shifts the peak.

    → Use j <= rows - i.

  4. 4. Mixing Tabs With Spaces

    Centering looks fine in one editor and broken in another.

    → Always print the space character " ".

  5. 5. Blind nextInt()

    Letters or empty input throw InputMismatchException.

    → Check hasNextInt() and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single star

0 spaces + 1 star — the tip is the whole pyramid.

rows = 0

Empty pattern

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

Negative

rows < 0

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

Large n

Wide base

Base width 2n-1 — fine for labs; may wrap on tiny terminals.

Bad input

Non-numeric ReadLine

nextInt() throws — use hasNextInt().

Last row

i == rows

Space loop runs 0 times; print 2*rows-1 stars only.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Drop to Program 3

  • Change stars from 2*i-1 to i
  • Confirm right-aligned triangle returns

2. Invert the pyramid

  • Outer loop from rows down to 1
  • Continue with Program 6

3. Verify star total

  • Count printed stars; assert equals rows * rows
  • Great self-check without looking up answers

4. Build a diamond

  • Add a lower half from rows - 1 down to 1
  • Match Program 10

Notes

  • n² stars. Sum of 1+3+…+(2n-1) equals n² — a handy complexity check.
  • Row character count before newline is (rows - i) + (2i - 1) = rows + i - 1 — tip rows are shorter than the base.
  • Validate rows > 0 for interactive programs; rows = 1 prints a single star.
  • Next: Program 6 inverts this pyramid with the same inner loops.

Quick Takeaway: print rows - i spaces, then 2 * i - 1 stars — that is the centered pyramid.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested space/star loops (Examples 1–2)O(rows²)O(1)
"*".repeat() shortcut (Example 3)O(rows²)O(rows) temporary per row string

Total stars = rows²; each row also prints up to Θ(rows) spaces.

Wrap Up

🎉 Conclusion

The center-aligned pyramid is leading spaces plus odd star counts: rows - i spaces and 2 * i - 1 stars. Master that pair and inverted pyramids or filled diamonds become small follow-ups.

Practice the three examples above, then continue to the inverted centered pyramid.

Spaces shrink, odd stars grow, total stars = n² — keep 2*i-1, and validate row counts when reading input.

💡 Best Practices

✅ Do

  • Explain rows - i spaces and 2*i-1 stars before coding
  • Keep odd star counts for a single-peak pyramid
  • Print real space characters, not tabs
  • State that total stars equal n² when asked about complexity
  • Check hasNextInt() for interactive demos

❌ Don’t

  • Use i stars when you meant a centered pyramid
  • Use 2 * i even widths for the classic shape
  • Skip leading spaces and expect centering
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about the centered pyramid

Print the full pyramid the beginner-friendly way.

5
Core concepts
02

Spaces

rows - i

Formula
* 03

Stars

2*i - 1

Formula
n 04

Total

n² stars

Math
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

2*i-1 gives odd lengths 1, 3, 5, … so each row adds one star on both sides. Using only i stars per row would not form the usual symmetric centered pyramid.
Printing (rows - i) spaces before the stars shifts the star block left as i grows, keeping the peak centered when the font is fixed-width.
Yes. Keep the same inner loops but run the outer loop from rows down to 1. The first printed row is the widest; later rows narrow toward the tip. See Program 6.
The last row has 2 * rows - 1 stars and no leading spaces when i equals rows.
O(n²) for n rows. Each row prints Theta(n) characters in the worst case; there are n rows. Total stars equal n².
Program 3 uses the same (rows - i) spaces but only i stars. Program 5 uses 2*i-1 stars so the shape widens on both sides.
Yes. System.out.print(" ".repeat(rows - i)); System.out.println("*".repeat(2 * i - 1));
Check sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Odd star counts 1, 3, 5, … come from 2 * i - 1. Their sum for n rows is — so total stars grow as a perfect square. This pyramid is also the upper half of the filled diamond.

Continue to Inverted Pyramid

Keep the same inner loops and count the outer loop down for an upside-down pyramid.

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