Butterfly Pattern with Numbers

This program prints a butterfly pattern with numbers.

Problem Statement

Write a Java program that prints a butterfly pattern with numbers using 5 rows.

Source Code

1 public class ButterflyNumbers {
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(j);
6 for(int j=1; j<=2*(n-i); j++) System.out.print(" ");
7 for(int j=i; j>=1; j--) System.out.print(j);
8 System.out.println();
9 }
10 for(int i=n; i>=1; i--) {
11 for(int j=1; j<=i; j++) System.out.print(j);
12 for(int j=1; j<=2*(n-i); j++) System.out.print(" ");
13 for(int j=i; j>=1; j--) System.out.print(j);
14 System.out.println();
15 }
16 }
17 }

Program Output

1        1
12      21
123    321
1234  4321
1234554321
1234  4321
123    321
12      21
1        1

Explanation

The first half prints ascending numbers, a shrinking gap of spaces, then descending numbers for each row, and the second half mirrors this with decreasing rows, together forming a numeric butterfly with symmetry.

Quick Links to Explore