Bash Script to Print Diamond Pattern with Stars
for ((i=1; i<=n; i++)); do for ((j=n-i; j>0; j--)); do echo -n ' '; done; for ((k=1; k<=2*i-1; k++)); do echo -n '*'; done; echo; done and then reverse for the bottom half.Examples
How to Think About It
Algorithm
Code
#!/bin/bash read -p "Enter diamond size: " n for ((i=1; i<=n; i++)) do for ((j=n-i; j>0; j--)) do echo -n " " done for ((k=1; k<=2*i-1; k++)) do echo -n "*" done echo done for ((i=n-1; i>=1; i--)) do for ((j=n-i; j>0; j--)) do echo -n " " done for ((k=1; k<=2*i-1; k++)) do echo -n "*" done echo done
Dry Run
Let's trace the diamond pattern for input 3 through the code
Top half line 1
i=1, spaces=2, stars=1, prints ' *'
Top half line 2
i=2, spaces=1, stars=3, prints ' ***'
Top half line 3
i=3, spaces=0, stars=5, prints '*****'
Bottom half line 1
i=2, spaces=1, stars=3, prints ' ***'
Bottom half line 2
i=1, spaces=2, stars=1, prints ' *'
| Line | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
| 4 | 1 | 3 | *** |
| 5 | 2 | 1 | * |
Why This Works
Step 1: Print spaces before stars
The code prints n - i spaces to align stars in the center for each line.
Step 2: Print stars in odd counts
It prints 2*i - 1 stars to form the increasing and then decreasing width of the diamond.
Step 3: Top and bottom halves
The first loop prints the top half, the second loop prints the bottom half in reverse order to complete the diamond.
Alternative Approaches
#!/bin/bash read -p "Enter diamond size: " n for ((i=1; i<=n; i++)); do printf "%*s" $((n - i)) "" printf "%0.s*" $(seq 1 $((2*i-1))) echo done for ((i=n-1; i>=1; i--)); do printf "%*s" $((n - i)) "" printf "%0.s*" $(seq 1 $((2*i-1))) echo done
#!/bin/bash read -p "Enter diamond size: " n for ((i=1; i<2*n; i++)); do if (( i <= n )); then spaces=$((n - i)) stars=$((2*i - 1)) else spaces=$((i - n)) stars=$((4*n - 2*i - 1)) fi for ((j=0; j<spaces; j++)); do echo -n " "; done for ((k=0; k<stars; k++)); do echo -n "*"; done echo done
Complexity: O(n^2) time, O(1) space
Time Complexity
The script uses nested loops where the inner loops run proportional to the line number, resulting in O(n^2) time.
Space Complexity
The script uses constant extra space for counters and prints directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar O(n^2) time, but using printf can be more efficient and cleaner than multiple echo calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops with echo | O(n^2) | O(1) | Simple and clear for beginners |
| Using printf | O(n^2) | O(1) | Cleaner output and formatting |
| Single loop with condition | O(n^2) | O(1) | Less code repetition, compact logic |