Print Hourglass Pattern in Java
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.
Java Program
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.
- 1The first loop runs
ifromndown to1, printingistars withn - ileading spaces — the top half narrows toward the center. - 2The second loop runs
ifrom2up ton, using the exact samei-stars-with-n - i-spaces rule — the bottom half widens back out. - 3The second loop starts at
2, not1, so the single-star middle row printed at the end of the first loop isn't repeated. - 4Both halves share the same per-row formula as a shrinking or growing triangle — only the direction and starting point differ.
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.
Why: Both halves together print a number of characters proportional to n², the same growth rate as a single triangle, just doubled.