Hollow Square Star Pattern

easy Pattern Printing

Problem

Read n and print a hollow square of stars. Only the border has stars. The inside is empty.

Constraints

  • 1 <= n <= 50

Examples

Input

3

Output

***
* *
***

Solutions

Best approachTime O(n^2)Space O(1)

Two loops visit every position of the square. A star is printed only when the position is in the first or last row, or the first or last column.

Same code works in Java810172125Basic features only, so nothing changes between versions.

Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write "*".repeat(count).

/*
 * Problem : Hollow square of stars.
 * Input   : One integer n (side length).
 * Output  : n lines.
 * Approach: Check if each position is on the border.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int size = new Scanner(System.in).nextInt();

        // Step 1: Repeat once for each row. Row numbers go from 1 to size.
        for (int row = 1; row <= size; row++) {
            StringBuilder line = new StringBuilder();

            // Step 2: Visit each column of the row. Column numbers go from 1 to size.
            for (int column = 1; column <= size; column++) {
                // Step 3: A position is on the border if it is in the first or last row or column.
                boolean isBorder = row == 1 || row == size || column == 1 || column == size;

                // Step 4: Add a star on the border and a space inside.
                line.append(isBorder ? "*" : " ");
            }

            // Step 5: Print the finished line.
            System.out.println(line);
        }
    }
}
Hints (2)
  1. Use two loops: one for rows and one for columns.
  2. When should a position print a star? Only on the border.