Butterfly Star Pattern
Problem
Read n and print a butterfly. Each row has i stars on the left, some spaces, and i stars on the right. The top half grows from 1 to n stars. The bottom half shrinks back to 1 star. There are 2n-1 rows.
Constraints
- 1 <= n <= 50
Examples
Input
3
Output
* * ** ** ****** ** ** * *
Solutions
Each line is left stars + middle spaces + right stars. The spaces shrink by 2 while the stars grow by 1 on each side. The bottom half mirrors the top half.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).
/*
* Problem : Butterfly of stars.
* Input : One integer n (rows in the top half).
* Output : 2n-1 lines.
* Approach: Left stars, middle spaces, right stars.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method returns the text repeated "count" times. Java 11 has String.repeat for this.
static String repeat(String text, int count) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++) {
result.append(text);
}
return result.toString();
}
// This method receives the half size and a row number. It returns one line of the butterfly.
static String buildLine(int half, int row) {
// Example: half = 3, row = 2 -> "**" + 2 spaces + "**"
return repeat("*", row) + repeat(" ", 2 * (half - row)) + repeat("*", row);
}
public static void main(String[] args) {
int half = new Scanner(System.in).nextInt();
// Step 1: Print the top half. The wings grow from 1 star to half stars.
for (int row = 1; row <= half; row++) {
System.out.println(buildLine(half, row));
}
// Step 2: Print the bottom half. The wings shrink. Start from half - 1 to skip the widest row.
for (int row = half - 1; row >= 1; row--) {
System.out.println(buildLine(half, row));
}
}
}
Hints (2)
- Look at one row: three parts (left, middle, right).
- Print the top half, then the same rows in reverse order.