PowerShell Script to Print Star Pattern Example
for loop in PowerShell like for ($i=1; $i -le 5; $i++) { Write-Host ('*' * $i) } to print a star pattern with increasing stars each line.Examples
How to Think About It
Algorithm
Code
for ($i = 1; $i -le 5; $i++) { Write-Host ('*' * $i) }
Dry Run
Let's trace printing 3 lines of stars through the code
First iteration
i = 1, print '*' repeated 1 time: *
Second iteration
i = 2, print '*' repeated 2 times: **
Third iteration
i = 3, print '*' repeated 3 times: ***
| Iteration | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Loop controls line count
The for loop runs from 1 to the number of lines, controlling how many lines print.
Step 2: Stars printed per line
On each loop, '*' * $i repeats the star character $i times to form the pattern.
Step 3: Write-Host outputs line
The Write-Host command prints the stars on the console line by line.
Alternative Approaches
for ($i = 1; $i -le 5; $i++) { $line = '' for ($j = 1; $j -le $i; $j++) { $line += '*' } Write-Host $line }
1..5 | ForEach-Object { Write-Output ('*' * $_) }
Complexity: O(n^2) time, O(n) space
Time Complexity
The outer loop runs n times, and each line prints up to n stars, so total operations are roughly proportional to n squared.
Space Complexity
The script uses space proportional to the longest line of stars, which is O(n), as it builds the string before printing.
Which Approach is Fastest?
Using string multiplication is faster and simpler than nested loops, but nested loops are easier to understand for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(n) | Simple and fast star pattern |
| Nested loops | O(n^2) | O(n) | Clear logic for beginners |
| Pipeline with ForEach-Object | O(n^2) | O(n) | Idiomatic PowerShell style |
'*' * number to repeat stars easily in PowerShell.-le for the loop condition, causing infinite loops or no output.