Hollow Square Star Pattern

Program to Print Hollow Square Star Pattern

PRINTING PATTERN:

*****
*   *
*   *
*****
            

PREREQUISITE:

Basic knowledge of Java language and loops.

ALGORITHM:

1. Take the number of rows/columns as input from the user (length of the square's side) and store it in a variable ('n').
2. Run a loop 'n' times to iterate through the rows (i=0 to i<n).
3. For the first and last rows, print stars for all columns.
4. For the rows in between, print a star at the beginning and end, and spaces in between.
5. Move to the next line after each row has been printed.

Code in Java:

import java.util.Scanner;

public class HollowSquarePattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows/columns for the hollow square:");
        int n = scanner.nextInt();  // Taking input for number of rows/columns

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // Print '*' for the first and last row, and first and last column
                if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");  // Print space for hollow part
                }
            }
            System.out.println();  // New line after each row
        }

        scanner.close();
    }
}
            

Output:

Enter the number of rows/columns for the hollow square:
5
*****
*   *
*   *
*****