Java ProgramsPatternsPrint Butterfly Pattern

Print Butterfly Pattern in Java

advanced·  Patterns  ·  Star Patterns

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.

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

Java Program

Java
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.

How It Works
  1. 1The top half runs i from 1 to n: i stars, then 2 * (n - i) spaces, then i more stars.
  2. 2As i grows, the wings get wider and the middle gap shrinks, until i == n closes the gap entirely and the row becomes solid stars.
  3. 3The bottom half runs the exact same row-building logic with i from n - 1 back down to 1, mirroring the top half.
  4. 4Reusing one row-building shape for both halves is what keeps the pattern symmetric — nothing about the top or bottom half is computed differently.
For 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.

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

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².

Key Concepts

nested for loopStringBuildermirrored halves

Related Programs