Bash Script to Print Half Diamond Pattern
for ((i=1; i<=n; i++)); do for ((j=1; j<=i; j++)); do echo -n "*"; done; echo; done; for ((i=n-1; i>=1; i--)); do for ((j=1; j<=i; j++)); do echo -n "*"; done; echo; done.Examples
How to Think About It
Algorithm
Code
#!/bin/bash read -p "Enter number of rows: " n for ((i=1; i<=n; i++)) do for ((j=1; j<=i; j++)) do echo -n "*" done echo done for ((i=n-1; i>=1; i--)) do for ((j=1; j<=i; j++)) do echo -n "*" done echo done
Dry Run
Let's trace input 3 through the code
First loop increasing stars
i=1: print 1 star '*' i=2: print 2 stars '**' i=3: print 3 stars '***'
Second loop decreasing stars
i=2: print 2 stars '**' i=1: print 1 star '*'
| i | Stars printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
| 2 | ** |
| 1 | * |
Why This Works
Step 1: Increasing stars loop
The first loop runs from 1 to n, printing stars equal to the current line number using nested loops and echo -n "*" to stay on the same line.
Step 2: Decreasing stars loop
The second loop runs from n-1 down to 1, printing stars in decreasing order to complete the half diamond shape.
Step 3: Line breaks
After printing stars on each line, echo prints a newline to move to the next line.
Alternative Approaches
#!/bin/bash read -p "Enter number of rows: " n for ((i=1; i<2*n; i++)) do if (( i <= n )); then stars=$i else stars=$((2*n - i)) fi for ((j=1; j<=stars; j++)) do echo -n "*" done echo done
#!/bin/bash read -p "Enter number of rows: " n i=1 while [ $i -le $n ] do j=1 while [ $j -le $i ] do echo -n "*" ((j++)) done echo ((i++)) done i=$((n-1)) while [ $i -ge 1 ] do j=1 while [ $j -le $i ] do echo -n "*" ((j++)) done echo ((i--)) done
Complexity: O(n^2) time, O(1) space
Time Complexity
The script uses nested loops: the outer loop runs up to n times and the inner loop runs up to i times, resulting in roughly n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The script uses a fixed number of variables and prints output directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using a single loop with condition reduces code length but not time complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Two nested for loops | O(n^2) | O(1) | Clarity and simplicity |
| Single loop with condition | O(n^2) | O(1) | Shorter code, moderate clarity |
| While loops | O(n^2) | O(1) | Beginners familiar with while |
echo -n to print stars on the same line before printing a newline.