Java ProgramsPatternsPrint Hourglass Pattern

Print Hourglass Pattern in Java

intermediate·  Patterns  ·  Star Patterns

Problem

An hourglass is the opposite of a diamond — instead of narrow-wide-narrow, it's wide-narrow-wide, built from a shrinking triangle immediately followed by a growing one that mirrors it.

Given a size n, print an hourglass shape that starts n stars wide, narrows to a single star, then widens back out to n stars.

Input
5
Output
***** **** *** ** * ** *** **** *****

Java Program

Java
public class HourglassPattern { public static void main(String[] args) { int n = 5; for (int i = n; i >= 1; i--) { // top half: narrows down to one star StringBuilder row = new StringBuilder(); for (int s = 0; s < n - i; s++) row.append(" "); for (int j = 0; j < i; j++) row.append("*"); System.out.println(row); } for (int i = 2; i <= n; i++) { // bottom half: widens back out, skipping the shared middle row StringBuilder row = new StringBuilder(); for (int s = 0; s < n - i; s++) row.append(" "); for (int j = 0; j < i; j++) row.append("*"); System.out.println(row); } } }

Output

***** **** *** ** * ** *** **** *****

Core Logic

Shrinking a row of stars down to one, then growing it back out the same way in reverse, produces the pinch in the middle that makes the shape an hourglass instead of a diamond.

How It Works
  1. 1The first loop runs i from n down to 1, printing i stars with n - i leading spaces — the top half narrows toward the center.
  2. 2The second loop runs i from 2 up to n, using the exact same i-stars-with-n - i-spaces rule — the bottom half widens back out.
  3. 3The second loop starts at 2, not 1, so the single-star middle row printed at the end of the first loop isn't repeated.
  4. 4Both halves share the same per-row formula as a shrinking or growing triangle — only the direction and starting point differ.
The top half ends with a single star at i = 1; the bottom half then begins at i = 2, widening from two stars back up to five.
💡

Key Point: This is the mirror image of Diamond Pattern's spacing logic — a diamond grows outward from one star in the middle, while an hourglass shrinks inward to one star in the middle.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: Both halves together print a number of characters proportional to n², the same growth rate as a single triangle, just doubled.

Key Concepts

nested for looptwo-phase patternpyramid centering

Related Programs