Bash Script to Print Right Triangle Pattern
Use a nested loop in Bash:
for i in {1..n}; do for j in $(seq 1 $i); do echo -n "*"; done; echo; done prints a right triangle of stars with height n.Examples
Inputn=1
Output*
Inputn=4
Output*
**
***
****
Inputn=0
Output
How to Think About It
To print a right triangle pattern, think of printing one star on the first line, two stars on the second, and so on until the nth line. Use one loop to count lines and a nested loop to print stars equal to the current line number.
Algorithm
1
Get the number of lines n from the user or set it.2
For each line number i from 1 to n:3
Print i stars on that line without a newline after each star.4
After printing stars for the line, print a newline to move to the next line.Code
bash
#!/bin/bash n=5 for ((i=1; i<=n; i++)) do for ((j=1; j<=i; j++)) do echo -n "*" done echo done
Output
*
**
***
****
*****
Dry Run
Let's trace n=3 through the code
1
Start outer loop i=1
Print 1 star: *
2
Next outer loop i=2
Print 2 stars: **
3
Next outer loop i=3
Print 3 stars: ***
| i | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Outer loop controls lines
The outer loop runs from 1 to n, each iteration representing one line of the triangle.
Step 2: Inner loop prints stars
The inner loop runs from 1 to the current line number i, printing stars without newlines.
Step 3: Newline after each line
After printing stars for a line, echo prints a newline to start the next line.
Alternative Approaches
Using seq and while loops
bash
#!/bin/bash n=5 i=1 while [ $i -le $n ] do j=1 while [ $j -le $i ] do echo -n "*" ((j++)) done echo ((i++)) done
Uses while loops instead of for loops; slightly longer but same logic.
Using printf with string repetition
bash
#!/bin/bash n=5 for ((i=1; i<=n; i++)) do printf '%*s\n' "$i" '' | tr ' ' '*' done
Uses printf and tr to print stars, avoiding inner loop; more concise but less intuitive.
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.
Space Complexity
Only a few variables are used, so space complexity is O(1).
Which Approach is Fastest?
Using printf with string repetition can be faster and shorter, but nested loops are clearer for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clarity and beginners |
| While loops | O(n^2) | O(1) | Alternative loop style |
| printf with tr | O(n^2) | O(1) | Conciseness and speed |
Use nested loops where the outer loop counts lines and the inner loop prints stars per line.
Forgetting to print a newline after each line causes all stars to print on one line.