PowerShell Script to Print Number Pattern Example
for ($i=1; $i -le 5; $i++) { for ($j=1; $j -le $i; $j++) { Write-Host -NoNewline $j } Write-Host '' } to print a number pattern.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 $j } Write-Host "" }
Dry Run
Let's trace input 3 through the code
Outer loop i=1
Inner loop j runs from 1 to 1, prints '1'
Outer loop i=2
Inner loop j runs from 1 to 2, prints '12'
Outer loop i=3
Inner loop j runs from 1 to 3, prints '123'
| i | Printed Numbers |
|---|---|
| 1 | 1 |
| 2 | 12 |
| 3 | 123 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to the input number, deciding how many rows to print.
Step 2: Inner loop prints numbers
The inner for loop prints numbers from 1 up to the current row number without moving to a new line.
Step 3: New line after each row
After printing each row, Write-Host "" moves the cursor to the next line to start a new row.
Alternative Approaches
param([int]$n = 5) $i = 1 while ($i -le $n) { $j = 1 while ($j -le $i) { Write-Host -NoNewline $j $j++ } Write-Host "" $i++ }
param([int]$n = 5) for ($i = 1; $i -le $n; $i++) { $line = -join (1..$n) Write-Host $line.Substring(0, $i) }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops run roughly n*(n+1)/2 times, which is O(n^2), because for each row i, it prints i numbers.
Space Complexity
The script uses constant extra space, only loop counters and temporary variables, so O(1).
Which Approach is Fastest?
Both for and while loops have similar performance; string manipulation may be slightly slower but simpler for some patterns.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Clear and concise control of loops |
| While loops | O(n^2) | O(1) | More flexible loop control |
| String substring | O(n^2) | O(1) | Simpler code for fixed patterns |
-NoNewline with Write-Host to print on the same line.