PowerShell Script to Print Pyramid Pattern
Use a nested loop in PowerShell like
for ($i=1; $i -le $n; $i++) { " " * ($n - $i) + "* " * $i } to print a pyramid pattern with stars.Examples
Input3
Output *
* *
* * *
Input5
Output *
* *
* * *
* * * *
* * * * *
Input1
Output*
How to Think About It
To print a pyramid pattern, think of each line as having spaces followed by stars. The number of spaces decreases each line, while the stars increase. Use loops to print spaces first, then stars, for each line.
Algorithm
1
Get the number of rows (n) from the user.2
For each line from 1 to n:3
Print (n - current line) spaces.4
Print (current line) stars with spaces.5
Move to the next line.Code
powershell
param([int]$n = 5) for ($i = 1; $i -le $n; $i++) { $spaces = ' ' * ($n - $i) $stars = '* ' * $i Write-Output "$spaces$stars" }
Output
*
* *
* * *
* * * *
* * * * *
Dry Run
Let's trace printing a pyramid with 3 rows through the code
1
First line
i=1, spaces = 3-1=2 spaces, stars = 1 star: ' * '
2
Second line
i=2, spaces = 3-2=1 space, stars = 2 stars: ' * * '
3
Third line
i=3, spaces = 3-3=0 spaces, stars = 3 stars: '* * * '
| Line | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 2 | * * |
| 3 | 0 | 3 | * * * |
Why This Works
Step 1: Calculate spaces
We print n - i spaces to align stars in a pyramid shape.
Step 2: Print stars
We print i stars with spaces to form the pyramid's width.
Step 3: Loop through lines
Repeating for each line builds the pyramid from top to bottom.
Alternative Approaches
Using Write-Host with -NoNewline
powershell
param([int]$n=5) for ($i=1; $i -le $n; $i++) { for ($j=1; $j -le $n - $i; $j++) { Write-Host -NoNewline ' ' } for ($k=1; $k -le $i; $k++) { Write-Host -NoNewline '* ' } Write-Host '' }
This method prints directly without building strings, giving more control but more code.
Using string formatting
powershell
param([int]$n=5) for ($i=1; $i -le $n; $i++) { $line = '{0}{1}' -f (' ' * ($n - $i)), ('* ' * $i) Write-Output $line }
Uses string format operator for clearer string construction but slightly less intuitive.
Complexity: O(n^2) time, O(n) space
Time Complexity
The outer loop runs n times, and each inner string multiplication runs up to n times, resulting in O(n^2) time.
Space Complexity
Each line creates strings proportional to n, so space is O(n) for the output line.
Which Approach is Fastest?
Building strings with multiplication is efficient and readable; using Write-Host with loops is more verbose but similar in speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(n) | Readability and simplicity |
| Write-Host loops | O(n^2) | O(1) | Direct output control |
| String formatting | O(n^2) | O(n) | Clear string construction |
Use string multiplication with
' ' * count and '* ' * count to easily build pyramid lines.Beginners often forget to reduce spaces each line, causing misaligned pyramids.