Python Program to Print Hollow Square Star Pattern

Introduction

A hollow square star pattern consists of stars (*) printed along the boundary of a square, while the inside of the square remains hollow (filled with spaces). This pattern helps in practicing the use of loops and conditional statements to control the placement of stars and spaces.

Problem Statement

Create a Python program that:

  • Accepts the number of rows and columns for the square.
  • Prints a hollow square star pattern.

Example:

  • Input: rows = 5
  • Output:
    *****
    *   *
    *   *
    *   *
    *****
    

Solution Steps

  1. Input the Number of Rows and Columns: The user specifies how many rows and columns the square should have.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the stars and spaces.
  3. Conditionally Print Stars: Print stars on the boundary (first and last row, and first and last column), while spaces are printed inside the square to create the hollow effect.

Python Program

# Step 1: Input the number of rows and columns for the square
rows = int(input("Enter the number of rows (and columns): "))

# Step 2: Outer loop for rows
for i in range(1, rows + 1):
    # Step 3: Inner loop for columns
    for j in range(1, rows + 1):
        # Step 4: Print stars at the boundary, else print spaces
        if i == 1 or i == rows or j == 1 or j == rows:
            print("*", end="")
        else:
            print(" ", end="")
    # Move to the next line after printing each row
    print()

Explanation

Step 1: Input the Number of Rows and Columns

  • The program asks the user for the number of rows and columns, which defines the size of the hollow square.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed. It runs from 1 to rows.

Step 3: Inner Loop for Columns

  • The inner loop controls how many columns are printed in each row. It runs from 1 to rows.

Step 4: Conditional Printing of Stars and Spaces

  • Stars (*) are printed at the boundary:
    • On the first row (i == 1),
    • On the last row (i == rows),
    • On the first column (j == 1),
    • On the last column (j == rows).
  • Spaces are printed inside the square, creating the hollow effect.

Output Example

For rows = 5, the output will be:

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

For rows = 6, the output will be:

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

Conclusion

This Python program prints a hollow square star pattern by using nested loops and conditional logic. The stars are printed along the boundary of the square, while spaces are printed inside to create the hollow effect. This exercise is helpful for practicing loop control and conditional statements in Python.

Comments