Butterfly Pattern of Stars

This program prints a butterfly pattern of stars.

Problem Statement

Write a Java program that prints a butterfly pattern of stars with 5 rows.

Source Code

1 public class ButterflyPattern {
2 public static void main(String[] args) {
3 int n = 5;
4 for(int i=1; i<=n; i++) {
5 for(int j=1; j<=i; j++) System.out.print("*");
6 for(int j=1; j<=2*(n-i); j++) System.out.print(" ");
7 for(int j=1; j<=i; j++) System.out.print("*");
8 System.out.println();
9 }
10 for(int i=n; i>=1; i--) {
11 for(int j=1; j<=i; j++) System.out.print("*");
12 for(int j=1; j<=2*(n-i); j++) System.out.print(" ");
13 for(int j=1; j<=i; j++) System.out.print("*");
14 System.out.println();
15 }
16 }
17 }

Program Output

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

Explanation

The first half builds the upper wings where stars increase and the space gap decreases, and the second half builds the lower wings with the opposite progression, together forming a symmetric butterfly shape.

Quick Links to Explore