Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a sum of numbers in an array

I am new in learning powershell and hoping to further my experience in other programs eventually. Currently doing a course in It and in my powershell class lopps have become a bit of an enemy of mine. In one script that we have to make, we need to create a script that will add numbers inputted in an array after the click of a button, in this scenario that button with be '0'. I have attempted various scripts but keep getting errors any help would be much appreaciated and keep in mind that i am new so the simpler the response for now the best it will help me and if possible explain why my code is wrong

Do {

    $input = Read-Host 'Enter variety of numbers and press 0 to add them together'

    if ($input -eq '0') {
        $sum = [int]$sum + ',' + [int]$sum
        Write-Host 'Sum of numbers entered' $sum
    }

}
while ($input -ne '0')
like image 856
se09 Avatar asked Sep 18 '25 05:09

se09


1 Answers

First off, $input is an automatic variable, so using it for user input is going to cause unexpected behavior.

Minding that, the Powershellish way is to use built-in cmdlets, such as Measure-Object that can sum things. Like so,

$i = Read-Host 'Enter variety of numbers, separated by space. Press <Enter> to add them together'
Write-host "The grand total is" ($i -split ' '  | measure-object -sum).sum

The input is read as a string into $i. Since string itself is a bit hard to sum, -split operator is used to split it into multiple things. A space ' ' is used as separator on which to split. The result is an array of objects that is piped to Measure-Object. It's smart enough to figure out that the things are actually integers, so summing makes sense. As the cmdlet returns multiple figures about its input, .sum is used to access only the sum.

like image 129
vonPryz Avatar answered Sep 20 '25 20:09

vonPryz