0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Print Star Pattern Example

Use a 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

Input5
Output* ** *** **** *****
Input3
Output* ** ***
Input1
Output*
🧠

How to Think About It

To print a star pattern, think of printing one star on the first line, two stars on the second, and so on until the given number. Use a loop that counts from 1 up to the input number, and on each loop print that many stars.
📐

Algorithm

1
Get the number of lines to print from the user.
2
Start a loop from 1 to the number of lines.
3
On each iteration, print stars equal to the current loop number.
4
End the loop after printing all lines.
💻

Code

powershell
for ($i = 1; $i -le 5; $i++) {
    Write-Host ('*' * $i)
}
Output
* ** *** **** *****
🔍

Dry Run

Let's trace printing 3 lines of stars through the code

1

First iteration

i = 1, print '*' repeated 1 time: *

2

Second iteration

i = 2, print '*' repeated 2 times: **

3

Third iteration

i = 3, print '*' repeated 3 times: ***

IterationStars 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

Using nested loops
powershell
for ($i = 1; $i -le 5; $i++) {
    $line = ''
    for ($j = 1; $j -le $i; $j++) {
        $line += '*'
    }
    Write-Host $line
}
This uses two loops: outer for lines, inner to build each line. It is more verbose but clearer for beginners.
Using Write-Output and string multiplication
powershell
1..5 | ForEach-Object { Write-Output ('*' * $_) }
This uses a pipeline and is more idiomatic PowerShell, but may be less clear for absolute beginners.

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.

ApproachTimeSpaceBest For
String multiplicationO(n^2)O(n)Simple and fast star pattern
Nested loopsO(n^2)O(n)Clear logic for beginners
Pipeline with ForEach-ObjectO(n^2)O(n)Idiomatic PowerShell style
💡
Use '*' * number to repeat stars easily in PowerShell.
⚠️
Beginners often forget to use -le for the loop condition, causing infinite loops or no output.