Bash Script to Print Pyramid Pattern with Loop
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 to print a pyramid pattern of height n.Examples
How to Think About It
Algorithm
Code
#!/bin/bash read -p "Enter pyramid height: " 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
Dry Run
Let's trace input 3 through the code
Line 1 (i=1)
Print 2 spaces (3-1=2), then 1 star (2*1-1=1)
Line 2 (i=2)
Print 1 space (3-2=1), then 3 stars (2*2-1=3)
Line 3 (i=3)
Print 0 spaces (3-3=0), then 5 stars (2*3-1=5)
| Line (i) | Spaces (n-i) | Stars (2*i-1) |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 1 | 3 |
| 3 | 0 | 5 |
Why This Works
Step 1: Spaces create pyramid shape
Printing spaces before stars shifts the stars to the right, forming the pyramid shape. The count decreases each line with n - i.
Step 2: Stars form the pyramid body
Stars increase by odd numbers each line using 2*i - 1, making the pyramid wider as it goes down.
Step 3: Nested loops control layout
The outer loop controls lines, inner loops print spaces and stars in order, then a newline moves to the next line.
Alternative Approaches
#!/bin/bash read -p "Enter pyramid height: " n for ((i=1; i<=n; i++)) do printf "%*s" $((n - i)) "" printf "%0.s*" $(seq 1 $((2*i - 1))) echo done
#!/bin/bash read -p "Enter pyramid height: " n i=1 while [ $i -le $n ] do j=$((n - i)) while [ $j -gt 0 ] do echo -n " " j=$((j - 1)) done k=$((2 * i - 1)) while [ $k -gt 0 ] do echo -n "*" k=$((k - 1)) done echo i=$((i + 1)) done
Complexity: O(n^2) time, O(1) space
Time Complexity
The script uses nested loops: the outer loop runs n times, and inner loops run up to n times, resulting in O(n^2) time.
Space Complexity
Only a few variables are used; no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
Using printf can be slightly faster and cleaner than multiple echo calls, but both have the same time complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops with echo | O(n^2) | O(1) | Simple and clear for beginners |
| Printf formatting | O(n^2) | O(1) | Cleaner output, slightly faster |
| While loops | O(n^2) | O(1) | Alternative loop style, easier for some |