Plus Shape Star Pattern
Problem
Read an odd number n and print a plus sign made of stars inside an n by n square. The middle row is full of stars. Every other row has one star in the middle column.
Constraints
- 1 <= n <= 49 and n is odd
Examples
Input
3
Output
* *** *
Solutions
The plus has one full row in the middle and one star in the middle column of all other rows.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).
/*
* Problem : Plus shape of stars.
* Input : One odd integer n (side length of the square).
* Output : n lines.
* Approach: Find the middle row and the middle column.
* 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 size = new Scanner(System.in).nextInt();
// Step 1: Find the middle index. Example: size 5 -> indexes 0..4 -> middle is 2.
int middle = size / 2;
// Step 2: Repeat once for each row. Row numbers start at 0.
for (int row = 0; row < size; row++) {
if (row == middle) {
// Step 3: The middle row is full of stars.
System.out.println(repeat("*", size));
} else {
// Step 4: Other rows have spaces and then one star in the middle column.
System.out.println(repeat(" ", middle) + "*");
}
}
}
}
Hints (2)
- The middle index of n items is n / 2 (integer division).
- Only one row is different from all other rows.