Pyramid Star Pattern
Problem
Read n and print a centered pyramid of stars with n rows. Row 1 has 1 star and each next row has 2 more stars.
Constraints
- 1 <= n <= 50
Examples
Input
3
Output
* *** *****
Solutions
Row r has n - r spaces and 2r - 1 stars. The spaces push the stars to the center.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).
/*
* Problem : Centered pyramid of stars.
* Input : One integer n (number of rows).
* Output : n lines.
* Approach: Print spaces first, then 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();
}
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
// Step 2: Count the spaces before the stars. Row 1 needs the most spaces.
int spaces = rows - row;
// Step 3: Count the stars. Each row adds 2 stars. Row 1 has 1 star, row 2 has 3 stars.
int stars = 2 * row - 1;
// Step 4: Print the spaces and then the stars.
System.out.println(repeat(" ", spaces) + repeat("*", stars));
}
}
}
Hints (2)
- Each row needs two numbers: spaces and stars.
- Spaces go down by 1 and stars go up by 2 in each row.