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 number2
Get the second number3
Add the two numbers using the plus operator4
Store the result in a variable5
Print the resultCode
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'
| Variable | Value |
|---|---|
| $num1 | 3 |
| $num2 | 5 |
| $sum | 8 |
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct addition | O(1) | O(1) | Simple scripts |
| User input conversion | O(1) | O(1) | Interactive scripts |
| Function encapsulation | O(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.