Print Butterfly Pattern in Java
Problem
A butterfly pattern is two triangles of stars facing each other, widest at the top and bottom and touching in the middle row, formed by combining a growing gap with a shrinking one across two mirrored halves.
Given a size n, print a butterfly-shaped star pattern with two n-row wings that meet in the middle.
Java Program
public class ButterflyPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
StringBuilder line = new StringBuilder();
for (int j = 1; j <= i; j++) line.append('*');
for (int j = 1; j <= 2 * (n - i); j++) line.append(' '); // shrinking gap between the wings
for (int j = 1; j <= i; j++) line.append('*');
System.out.println(line);
}
for (int i = n - 1; i >= 1; i--) {
StringBuilder line = new StringBuilder();
for (int j = 1; j <= i; j++) line.append('*');
for (int j = 1; j <= 2 * (n - i); j++) line.append(' ');
for (int j = 1; j <= i; j++) line.append('*');
System.out.println(line);
}
}
}Output
Core Logic
Each row is built from three pieces — a left wing of stars, a gap that shrinks as the wings grow, and a matching right wing — and running that same row-building logic forward then backward produces the full butterfly.
- 1The top half runs
ifrom1ton:istars, then2 * (n - i)spaces, thenimore stars. - 2As
igrows, the wings get wider and the middle gap shrinks, untili == ncloses the gap entirely and the row becomes solid stars. - 3The bottom half runs the exact same row-building logic with
ifromn - 1back down to1, mirroring the top half. - 4Reusing one row-building shape for both halves is what keeps the pattern symmetric — nothing about the top or bottom half is computed differently.
n = 5, row 3 has 3 stars, a gap of 2 * (5 - 3) = 4 spaces, then 3 more stars; row 5, the middle, has a gap of 0 and reads as ten solid stars.Key Point: The gap size 2 * (n - i) is what makes the wings meet exactly at the middle row — at i = n the gap hits zero, and any other formula would leave a visible seam or overlap.
Why: Every row builds a line whose length is proportional to n, across roughly 2n rows total, so the total characters printed scale with n².