0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Find Sum of n Numbers

Use $sum = 0; 1..n | ForEach-Object { $sum += $_ }; Write-Output $sum to find the sum of numbers from 1 to n in PowerShell.
📋

Examples

Input5
Output15
Input10
Output55
Input0
Output0
🧠

How to Think About It

To find the sum of n numbers, think of adding each number from 1 up to n one by one. You start with zero and keep adding each number until you reach n.
📐

Algorithm

1
Get the input number n.
2
Initialize a sum variable to 0.
3
Loop from 1 to n, adding each number to sum.
4
After the loop ends, return the sum.
💻

Code

powershell
$n = Read-Host 'Enter a number'
$n = [int]$n
$sum = 0
1..$n | ForEach-Object { $sum += $_ }
Write-Output "Sum of numbers from 1 to $n is $sum"
Output
Enter a number: 5 Sum of numbers from 1 to 5 is 15
🔍

Dry Run

Let's trace input 5 through the code

1

Initialize sum

$sum = 0

2

Loop from 1 to 5

Add 1, then 2, then 3, then 4, then 5 to sum

3

Final sum

$sum = 15

IterationCurrent NumberSum So Far
111
223
336
4410
5515
💡

Why This Works

Step 1: Initialize sum

We start with $sum = 0 because we have not added any numbers yet.

Step 2: Add numbers in loop

The 1..$n creates a list from 1 to n, and ForEach-Object adds each number to $sum.

Step 3: Output the result

After adding all numbers, Write-Output prints the total sum.

🔄

Alternative Approaches

Using the formula n*(n+1)/2
powershell
$n = Read-Host 'Enter a number'
$n = [int]$n
$sum = $n * ($n + 1) / 2
Write-Output "Sum of numbers from 1 to $n is $sum"
This method is faster because it uses a math formula without looping.
Using a while loop
powershell
$n = Read-Host 'Enter a number'
$n = [int]$n
$sum = 0
$i = 1
while ($i -le $n) {
  $sum += $i
  $i++
}
Write-Output "Sum of numbers from 1 to $n is $sum"
This uses a while loop instead of ForEach-Object, which some beginners find easier to understand.

Complexity: O(n) time, O(1) space

Time Complexity

The loop runs n times, so the time grows linearly with n, making it O(n).

Space Complexity

Only a few variables are used, so space is constant O(1).

Which Approach is Fastest?

The formula method is O(1) time and fastest, while looping methods are O(n).

ApproachTimeSpaceBest For
Loop with ForEach-ObjectO(n)O(1)Simple and clear for beginners
Formula n*(n+1)/2O(1)O(1)Fastest for large n
While loopO(n)O(1)Alternative loop style
💡
Use the formula n*(n+1)/2 for the fastest sum calculation without loops.
⚠️
Forgetting to convert input to a number can cause errors or unexpected results.