Inverted Pyramid Star Pattern
Problem
Read n and print an upside-down centered pyramid of stars. The first row has 2n-1 stars and the last row has 1 star.
Constraints
- 1 <= n <= 50
Examples
Input
3
Output
***** *** *
Solutions
This is the pyramid turned upside down: spaces grow by 1 and stars shrink by 2 in each row.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).
/*
* Problem : Inverted centered pyramid of stars.
* Input : One integer n (number of rows).
* Output : n lines.
* Approach: Spaces go up and stars go down in each row.
* 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. Row 1 has no spaces. Each next row has one more.
int spaces = row - 1;
// Step 3: Count the stars. Row 1 has 2n-1 stars. Each next row has 2 stars less.
int stars = 2 * (rows - row) + 1;
// Step 4: Print the spaces and then the stars.
System.out.println(repeat(" ", spaces) + repeat("*", stars));
}
}
}
Hints (2)
- Use one outer loop for the rows. What changes from one row to the next?
- Write the pattern for n = 3 on paper and count the stars in each row.