PowerShell Script to Print Right Triangle Pattern
for ($i=1; $i -le $n; $i++) { for ($j=1; $j -le $i; $j++) { Write-Host '*' -NoNewline } Write-Host '' } to print a right triangle pattern of stars.Examples
How to Think About It
Algorithm
Code
param([int]$n = 5) for ($i = 1; $i -le $n; $i++) { for ($j = 1; $j -le $i; $j++) { Write-Host '*' -NoNewline } Write-Host '' }
Dry Run
Let's trace printing a right triangle with 3 lines through the code
Start outer loop with i=1
Print 1 star: *
Outer loop i=2
Print 2 stars: **
Outer loop i=3
Print 3 stars: ***
| Line (i) | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Outer loop controls lines
The for loop with variable i runs from 1 to n, each iteration representing one line.
Step 2: Inner loop prints stars
For each line, the inner for loop prints stars equal to the current line number i using Write-Host '*' -NoNewline.
Step 3: Move to next line
After printing stars for a line, Write-Host '' moves the cursor to the next line for the next iteration.
Alternative Approaches
param([int]$n = 5) for ($i = 1; $i -le $n; $i++) { Write-Host ('*' * $i) }
param([int]$n = 5) $i = 1 while ($i -le $n) { $j = 1 while ($j -le $i) { Write-Host '*' -NoNewline $j++ } Write-Host '' $i++ }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops run approximately n*(n+1)/2 times, which is O(n^2), because for each line i, i stars are printed.
Space Complexity
The script uses constant extra space, O(1), as it only stores loop counters and prints directly.
Which Approach is Fastest?
Using string multiplication is generally faster and cleaner than nested loops, but both have the same O(n^2) time complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clear step-by-step printing |
| String multiplication | O(n^2) | O(1) | Concise and readable code |
| While loops | O(n^2) | O(1) | Beginners learning loop basics |
Write-Host '*' -NoNewline to print stars on the same line without moving to the next line.-NoNewline causes each star to print on a new line instead of forming a triangle.