Python Program to Print Hollow Rectangle pattern

When we start programming, printing different star patterns helps us build our logic and problem-solving skills. One of the easiest and beginner patterns is the hollow rectangle pattern. In this article, we are going to learn how we can print the hollow rectangle pattern using different approaches in Python.

What is a Hollow Rectangle Pattern?

A hollow rectangle pattern is a rectangle-shaped pattern made of stars where the stars are present only on the boundaries of the rectangle. The rectangle is hollow, meaning the stars are printed only on the borders, while the inner area remains empty ?

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

Using Nested Loop Approach

In this approach, we use a nested loop to print a hollow rectangle star pattern. The outer loop handles each row, and the inner loop handles each column. We check if it's the first or last row, or first or last column, then we print a star; otherwise, we print a space ?

Example

rows = 6
cols = 5 

for i in range(rows):
    for j in range(cols):
        if i == 0 or i == rows - 1 or j == 0 or j == cols - 1:
            print("*", end="")
        else:
            print(" ", end="")
    print()

The output of the above program is ?

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

How It Works:

  • For border positions (i == 0, i == rows-1, j == 0, j == cols-1), print "*"
  • For inner positions, print a space " "
  • The end="" parameter keeps elements on the same line
  • print() moves to the next line after each row

Time Complexity: O(rows × cols)

Using String Concatenation Approach

In this approach, we construct each row as a complete string before printing. For the first and last row, we create a string of stars. For middle rows, we create a string with stars only at the start and end, with spaces in between ?

Example

rows = 4
cols = 5

for i in range(rows):
    if i == 0 or i == rows - 1:
        print("*" * cols)
    else:
        print("*" + " " * (cols - 2) + "*")

The output of the above program is ?

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

How It Works:

  • Top and bottom rows: "*" * cols creates a solid line of stars
  • Middle rows: "*" + " " * (cols - 2) + "*" creates borders with spaces
  • (cols - 2) accounts for the two border stars

Time Complexity: O(rows × cols)

Comparison

Approach Lines of Code Readability Best For
Nested Loop More Clear logic flow Learning conditionals
String Concatenation Fewer Concise Quick implementation

Conclusion

Both approaches effectively create hollow rectangle patterns. The nested loop method helps understand conditional logic, while string concatenation provides a more concise solution. Choose based on your learning goals and code readability preferences.

Kickstart Your Career

Get certified by completing the course

Get Started