0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Add Two Numbers with Output

Use $sum = $num1 + $num2 in PowerShell to add two numbers, then output the result with Write-Output $sum.
📋

Examples

Input3 and 5
Output8
Input10 and 20
Output30
Input-4 and 7
Output3
🧠

How to Think About It

To add two numbers in PowerShell, you simply use the plus operator + between them. You store the result in a variable and then print it out. Think of it like adding two amounts of money and showing the total.
📐

Algorithm

1
Get the first number
2
Get the second number
3
Add the two numbers using the plus operator
4
Store the result in a variable
5
Print the result
💻

Code

powershell
$num1 = 3
$num2 = 5
$sum = $num1 + $num2
Write-Output "The sum is: $sum"
Output
The sum is: 8
🔍

Dry Run

Let's trace adding 3 and 5 through the code

1

Assign first number

$num1 = 3

2

Assign second number

$num2 = 5

3

Add numbers

$sum = 3 + 5

4

Output result

Print 'The sum is: 8'

VariableValue
$num13
$num25
$sum8
💡

Why This Works

Step 1: Store numbers

We assign the two numbers to variables $num1 and $num2 so we can use them later.

Step 2: Add numbers

Using the + operator adds the two values together and stores the result in $sum.

Step 3: Show result

We use Write-Output to print the sum so the user can see the answer.

🔄

Alternative Approaches

Read input from user
powershell
$num1 = Read-Host 'Enter first number'
$num2 = Read-Host 'Enter second number'
$sum = [int]$num1 + [int]$num2
Write-Output "The sum is: $sum"
This method lets the user enter numbers at runtime but requires converting input to integers.
Using a function
powershell
function Add-Numbers($a, $b) { return $a + $b }
$result = Add-Numbers 4 6
Write-Output "Sum: $result"
Encapsulates addition in a reusable function for cleaner code.

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

Time Complexity

Adding two numbers is a single operation, so it runs in constant time.

Space Complexity

Only a few variables are used, so space usage is constant.

Which Approach is Fastest?

All methods run in constant time; using a function adds minimal overhead but improves code reuse.

ApproachTimeSpaceBest For
Direct additionO(1)O(1)Simple scripts
User input conversionO(1)O(1)Interactive scripts
Function encapsulationO(1)O(1)Reusable code
💡
Always convert user input to numbers before adding to avoid errors.
⚠️
Forgetting to convert input strings to numbers causes concatenation instead of addition.