Hollow Butterfly Pattern
This program prints a hollow butterfly pattern of stars.
Problem Statement
Write a Java program that prints a hollow butterfly pattern of stars with 5 rows.
Source Code
| 1 | public class HollowButterfly { |
| 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++) { |
| 6 | if(j==1 || j==i) System.out.print("*"); |
| 7 | else System.out.print(" "); |
| 8 | } |
| 9 | for(int j=1; j<=2*(n-i); j++) System.out.print(" "); |
| 10 | for(int j=1; j<=i; j++) { |
| 11 | if(j==1 || j==i) System.out.print("*"); |
| 12 | else System.out.print(" "); |
| 13 | } |
| 14 | System.out.println(); |
| 15 | } |
| 16 | for(int i=n; i>=1; i--) { |
| 17 | for(int j=1; j<=i; j++) { |
| 18 | if(j==1 || j==i) System.out.print("*"); |
| 19 | else System.out.print(" "); |
| 20 | } |
| 21 | for(int j=1; j<=2*(n-i); j++) System.out.print(" "); |
| 22 | for(int j=1; j<=i; j++) { |
| 23 | if(j==1 || j==i) System.out.print("*"); |
| 24 | else System.out.print(" "); |
| 25 | } |
| 26 | System.out.println(); |
| 27 | } |
| 28 | } |
| 29 | } |
Program Output
* * * * * * * * * * * ** * * * * ** * * * * * * * * * * *
Explanation
Both halves print stars only at the edges (j==1 || j==i) with spaces inside each wing and a shrinking-then-expanding gap in the middle, together forming a hollow butterfly shape symmetric across the middle row.