Bash Script to Print Hollow Square Pattern
for ((i=1;i<=n;i++)); do for ((j=1;j<=n;j++)); do if [[ $i -eq 1 || $i -eq n || $j -eq 1 || $j -eq n ]]; then echo -n '*'; else echo -n ' '; fi; done; echo; done.Examples
How to Think About It
Algorithm
Code
#!/bin/bash read -p "Enter size of square: " n for ((i=1; i<=n; i++)); do for ((j=1; j<=n; j++)); do if [[ $i -eq 1 || $i -eq n || $j -eq 1 || $j -eq n ]]; then echo -n '*' else echo -n ' ' fi done echo done
Dry Run
Let's trace the code for input size 3 through the loops.
First row (i=1)
j=1: border, print '*'; j=2: border, print '*'; j=3: border, print '*'
Second row (i=2)
j=1: border, print '*'; j=2: inside, print ' '; j=3: border, print '*'
Third row (i=3)
j=1: border, print '*'; j=2: border, print '*'; j=3: border, print '*'
| Row i | Column j | |
|---|---|---|
| 1 | 1 | * |
| 1 | 2 | * |
| 1 | 3 | * |
| 2 | 1 | * |
| 2 | 2 | |
| 2 | 3 | * |
| 3 | 1 | * |
| 3 | 2 | |
| 3 | 3 | * |
Why This Works
Step 1: Outer and inner loops
The outer loop runs through each row, and the inner loop runs through each column in that row.
Step 2: Border check
We check if the current position is on the first or last row or column using if conditions.
Step 3: Print star or space
If on border, print *; otherwise, print a space to create the hollow effect.
Alternative Approaches
#!/bin/bash read -p "Enter size: " n for ((i=1; i<=n*n; i++)); do row=$(((i-1)/n+1)) col=$(((i-1)%n+1)) if [[ $row -eq 1 || $row -eq n || $col -eq 1 || $col -eq n ]]; then echo -n '*' else echo -n ' ' fi if (( i % n == 0 )); then echo; fi done
#!/bin/bash read -p "Enter size: " n for ((i=1; i<=n; i++)); do line="" for ((j=1; j<=n; j++)); do if [[ $i -eq 1 || $i -eq n || $j -eq 1 || $j -eq n ]]; then line+="*" else line+=" " fi done printf "%s\n" "$line" done
Complexity: O(n^2) time, O(1) space
Time Complexity
The script uses two nested loops each running n times, so it performs n*n iterations, resulting in O(n^2) time.
Space Complexity
The script uses a fixed amount of extra memory regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar O(n^2) time, but single loop with arithmetic may be slightly faster due to fewer loop overheads, while building lines as strings improves readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(n^2) | O(1) | Simplicity and clarity |
| Single loop with arithmetic | O(n^2) | O(1) | Compact code, slight speed gain |
| Building line string | O(n^2) | O(n) | Readability and easy modification |
echo -n to print characters without a newline inside loops.