Butterfly Pattern in Java of Numbers using For loop
ADVERTISEMENTS
Butterfly pattern in java of numbers using for loop. In this article, you will learn how to print the butterfly pattern in java of numbers using for loop.
Example
Enter the height of the pattern: 6
This the butterfly pattern:
1 1
12 21
123 321
1234 4321
12345 54321
12345654321
12345 54321
1234 4321
123 321
12 21
1 1
You should have knowledge of the following topics in Java programming to understand this program:
- Java
java.util.Scanner
package - Java
main()
method - Java
for
loop statement - Java
System.out.print()
function
In this program, we used normal functions and statements to print the butterfly pattern in java language.
Source Code
// Butterfly Pattern in Java of Numbers using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int rows, height, digits, space;
System.out.print("Enter the height of the pattern: ");
height = in.nextInt();
System.out.println("\nThis the butterfly pattern:\n\n");
for(rows = 1; rows <= height - 1; rows++) {
System.out.print("\t");
for(digits = 1; digits <= rows; digits++)
System.out.print(digits);
for(space = 1; space <= 2 * (height - rows); space++)
System.out.print(" ");
System.out.print('\b');
for(digits = rows; digits >= 1; digits--)
System.out.print(digits);
System.out.print('\n');
}
for(rows = height; rows >= 1; rows--) {
System.out.print("\t");
for(digits = 1; digits <= rows; digits++)
System.out.print(digits);
for(space = 1; space <= 2 * (height - rows); space++)
System.out.print(" ");
System.out.print('\b');
for(digits = rows; digits >= 1; digits--)
System.out.print(digits);
System.out.print('\n');
}
}
}
Output
Enter the height of the pattern: 6
This the butterfly pattern:
1 1
12 21
123 321
1234 4321
12345 54321
12345654321
12345 54321
1234 4321
123 321
12 21
1 1
Note: In this program, we used
nested-for
loop statements.
Explanation
In this program, we have taken input 6
size of the pattern then made the calculation using the for
loop statement.