Center-Aligned Pyramid Star Pattern in Java

Beginner
6 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A center-aligned pyramid grows to a wide base with a single peak: row i has rows - i leading spaces and 2 * i - 1 stars.

Remember
Rule: spaces = rows - i, stars = 2 * i - 1

    *
   ***
  *****
 *******
*********     ← 5 rows

It reuses Program 3’s spacing idea, but uses odd star counts so the shape widens on both sides. The same row formula is the upper half of the filled diamond.

How to Solve It

Two inner loops per row — spaces then odd stars — or the same formulas with String.repeat.

MethodIdeaBest for
Nested loopsrows - i spaces, then 2 * i - 1 starsLearning, interviews, exams
String.repeatBuild spaces and stars as whole stringsShorter demos once loops click (Java 11+)

Pseudocode

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

Cheat sheet

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 stars on the last row
Invert laterfor (i = rows; i >= 1; i--) → Program 6
Row shortcutSystem.out.print(" ".repeat(rows - i)); System.out.println("*".repeat(2 * i - 1));

print vs println

APIEffectUse for
System.out.printStays on the same lineEach space and each *
System.out.printlnEnds the current lineAfter spaces and stars for that row

Live Preview

Change the row count and the pyramid updates instantly — including the perfect-square star total.

Whole numbers from 1 to 15. Base width = 2 * rows - 1; total stars = rows².

Live result 5 rows · 25 stars
    *
   ***
  *****
 *******
*********

Worked Walkthrough — rows = 4

Trace spaces and odd star counts for each outer-loop value of i.

iSpaces rows - iStars 2 * i - 1Printed row
131*
223***
315*****
407*******

Total stars: 1 + 3 + 5 + 7 = 16 = 4². Base width: 2×4 - 1 = 7.

Java Programs

Three complete programs: fixed rows, Scanner input, and a String.repeat shortcut. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded height — rows - i spaces, then 2 * i - 1 stars.

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

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

How It Works

1. Set height. rows = 5 means five lines; the base has 2 * 5 - 1 = 9 stars.

2. Outer loop picks the row. i runs from 1 to rows.

3. Spaces then stars. Print rows - i spaces, then 2 * i - 1 stars via System.out.print.

4. Break the line. System.out.println() after both inner loops starts the next row.

When i = 1: 4 spaces + 1 star. When i = 5: 0 spaces + 9 stars.

Example 2 — User Input Version

Read the height at runtime with Scanner. Prefer hasNextInt() in real apps (shown in the tip below).

Java
import java.util.Scanner;

public class CenterPyramidInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

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

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

How It Works

1. Prompt and read. Ask for a row count, then store it with sc.nextInt().

2. Same nested-loop core. Only the source of rows changes — the print logic matches Example 1.

3. Safer input tip. Non-numeric input throws InputMismatchException. Prefer:

Safer input
if (!sc.hasNextInt()) {
    System.out.println("Enter a positive whole number.");
    return;
}
int rows = sc.nextInt();
if (rows < 1) {
    System.out.println("Enter a positive whole number.");
    return;
}

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

Build each row in two calls — same shape, no explicit space/star character loops (Java 11+).

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

1. One outer loop. Still walk i from 1 to rows.

2. Build the row. " ".repeat(rows - i) for padding; "*".repeat(2 * i - 1) for the odd star run.

3. Learn loops first. Use Examples 1–2 when you need to show nested bounds; treat this as a polish shortcut afterward.

Edge Cases & Pitfalls

Check these before calling the solution done.

2 * i

Even width

Use 2 * i - 1 (odd). Even widths lose the classic single-center peak.

j < rows - i

One space short

Space loop must be j <= rows - i. A strict < shifts the peak.

Only i stars

Program 3 shape

Same spaces with i stars is the right-aligned triangle, not a full pyramid.

rows = 1

Single star

0 spaces + 1 star — a good tip sanity check.

rows ≤ 0

Empty output

Outer loop never runs. Validate and re-prompt for interactive programs.

Bad input

Use hasNextInt()

nextInt() throws on letters — prefer sc.hasNextInt() and require rows >= 1.

Time and Space Complexity

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

Each of n rows prints Θ(n) characters (spaces + stars). Total stars = 1 + 3 + … + (2n - 1) = n².

Key Takeaways

  • Formulas: rows - i spaces and 2 * i - 1 stars.
  • Odd widths: keep 2 * i - 1 for a single centered peak.
  • Break the row: print for spaces/stars; println after both loops.
  • Complexity: O(n²) time; total stars = n²; O(1) extra space for nested loops.

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

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.
System.out.print stays on the same line. System.out.println ends the current line. Spaces and stars use print; the row break uses println after both inner loops.
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)); builds each row without explicit inner character loops (Java 11+).

Did you know?

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

Next: Inverted Pyramid

Flip the outer loop and print a wide-to-narrow centered 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