PowerShell Script to Print Multiplication Table
for loop in PowerShell like for ($i=1; $i -le 10; $i++) { for ($j=1; $j -le 10; $j++) { "$i * $j = $($i * $j)" } } to print the multiplication table.Examples
How to Think About It
Algorithm
Code
for ($i = 1; $i -le 10; $i++) { for ($j = 1; $j -le 10; $j++) { Write-Output "$i * $j = $($i * $j)" } }
Dry Run
Let's trace the multiplication table for 1 to 3 through the code
Outer loop starts with i=1
i=1
Inner loop runs j=1 to 3
j=1, print '1 * 1 = 1'; j=2, print '1 * 2 = 2'; j=3, print '1 * 3 = 3'
Outer loop increments to i=2 and inner loop repeats
i=2; j=1, print '2 * 1 = 2'; j=2, print '2 * 2 = 4'; j=3, print '2 * 3 = 6'
| i | j | Output |
|---|---|---|
| 1 | 1 | 1 * 1 = 1 |
| 1 | 2 | 1 * 2 = 2 |
| 1 | 3 | 1 * 3 = 3 |
| 2 | 1 | 2 * 1 = 2 |
| 2 | 2 | 2 * 2 = 4 |
| 2 | 3 | 2 * 3 = 6 |
| 3 | 1 | 3 * 1 = 3 |
| 3 | 2 | 3 * 2 = 6 |
| 3 | 3 | 3 * 3 = 9 |
Why This Works
Step 1: Outer loop controls the first number
The for loop with variable $i runs from 1 to 10, representing the first number in the multiplication.
Step 2: Inner loop controls the second number
Inside the outer loop, another for loop with variable $j runs from 1 to 10, representing the second number.
Step 3: Print the multiplication result
For each pair ($i, $j), the script calculates $i * $j and prints it in the format i * j = result.
Alternative Approaches
$i = 1 while ($i -le 10) { $j = 1 while ($j -le 10) { Write-Output "$i * $j = $($i * $j)" $j++ } $i++ }
for ($i = 1; $i -le 10; $i++) { $line = "" for ($j = 1; $j -le 10; $j++) { $line += "{0,4}" -f ($i * $j) } Write-Output $line }
function Print-MultiplicationTable($max) { for ($i = 1; $i -le $max; $i++) { for ($j = 1; $j -le $max; $j++) { Write-Output "$i * $j = $($i * $j)" } } } Print-MultiplicationTable -max 5
Complexity: O(n^2) time, O(1) space
Time Complexity
The script uses two nested loops each running up to n times, resulting in O(n^2) operations to print all multiplication pairs.
Space Complexity
The script uses constant extra space, only storing loop counters and temporary strings, so O(1) space.
Which Approach is Fastest?
All approaches have similar time complexity; using for loops is concise and clear, while formatted output trades some speed for readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For Loops | O(n^2) | O(1) | Simple and clear multiplication tables |
| While Loops | O(n^2) | O(1) | Same as for loops but less concise |
| Formatted Table Output | O(n^2) | O(1) | Better visual layout for tables |
| Function with Parameter | O(n^2) | O(1) | Reusable and dynamic table size |