PowerShell Script to Print Diamond Pattern
for ($i=1; $i -le $n; $i++) { ... } and for ($i=$n-1; $i -ge 1; $i--) { ... } to form a diamond pattern.Examples
How to Think About It
Algorithm
Code
param([int]$n = 5) for ($i = 1; $i -le $n; $i++) { $spaces = ' ' * ($n - $i) $stars = '*' * (2 * $i - 1) Write-Output "$spaces$stars" } for ($i = $n - 1; $i -ge 1; $i--) { $spaces = ' ' * ($n - $i) $stars = '*' * (2 * $i - 1) Write-Output "$spaces$stars" }
Dry Run
Let's trace the diamond pattern for input n=3 through the code
Top half line 1
spaces = 3 - 1 = 2 spaces, stars = 2*1 - 1 = 1 star -> ' *'
Top half line 2
spaces = 3 - 2 = 1 space, stars = 3 stars -> ' ***'
Top half line 3
spaces = 3 - 3 = 0 spaces, stars = 5 stars -> '*****'
Bottom half line 1
spaces = 3 - 2 = 1 space, stars = 3 stars -> ' ***'
Bottom half line 2
spaces = 3 - 1 = 2 spaces, stars = 1 star -> ' *'
| Line | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
| 4 | 1 | 3 | *** |
| 5 | 2 | 1 | * |
Why This Works
Step 1: Calculate spaces
Each line has spaces equal to n - i to center the stars.
Step 2: Calculate stars
Stars increase by 2 each line using 2 * i - 1 to keep the diamond shape.
Step 3: Print top and bottom halves
First print lines from 1 to n, then from n-1 down to 1 to complete the diamond.
Alternative Approaches
param([int]$n = 5) for ($i = 1; $i -lt 2 * $n; $i++) { $line = $i -le $n ? $i : 2 * $n - $i $spaces = ' ' * ($n - $line) $stars = '*' * (2 * $line - 1) Write-Output "$spaces$stars" }
param([int]$n = 5) $lines = @() for ($i = 1; $i -le $n; $i++) { $spaces = ' ' * ($n - $i) $stars = '*' * (2 * $i - 1) $lines += "$spaces$stars" } $lines += $lines[0..($n-2)] | Sort-Object -Descending $lines | ForEach-Object { Write-Output $_ }
Complexity: O(n^2) time, O(n) space
Time Complexity
The script runs two loops each up to n, and each line prints up to 2*n characters, so time is O(n^2).
Space Complexity
Uses only a few variables and prints lines directly, so space is O(n) for output lines if stored.
Which Approach is Fastest?
The single loop with conditional is slightly faster due to fewer loops but less readable than two separate loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Two loops (main) | O(n^2) | O(n) | Clarity and simplicity |
| Single loop with conditional | O(n^2) | O(n) | Compact code, slight speed gain |
| Build lines in array | O(n^2) | O(n) | Reuse or modify lines before printing |
' ' * count and '*' * count to easily create spaces and stars.