Reputation: 27
I want to print all the numbers from 1 through 50 and show it in the screen.
The next step is I want to sum up all the numbers and store the value into a variable to show it on the screen, but cannot understand how to do this.
I have done the following, can you suggest me how I can do the next step?
$i=1
do
{
write-host "The numbers : $i"
$i++
}
while ($i -le 50)
Upvotes: 0
Views: 33
Reputation: 1630
I would use the following one line code to do your work
1..50 | % -b {$sum=0} -p {$sum+=$_; $_} -e {"The total sum is: $sum"};
Upvotes: 0
Reputation: 174485
You could add a $sum
variable and add the value of $i
to it everytime the loop runs:
$sum = 0
$i = 1
do
{
$sum += $i
write-host "The numbers : $i"
$i++
}
while ($i -le 50)
Write-Host "The total sum is : $sum"
You could also generate all the numbers in advance with the ..
range operator:
$AllTheNumbers = 1..50
$AllTheNumbers |ForEach-Object {
Write-Host "The number: $_"
}
And calculate the sum with Measure-Object
:
$Sum = ($AllTheNumbers |Measure-Object -Sum).Sum
Write-Host "Sum: $Sum"
Upvotes: 1