while
loops run their body of code while a defined condition is true. This is similar to for
loops, but more control is put in our hands regarding what variable is used in the condition and how the variable is updated in the loop.
$counter = 0 while ($counter -lt 3) { $counter++ Write-Host "Be sure to update counter" }
The while
loop above uses the condition $counter -lt 3
. If $counter
is less than 3
, the loop will keep iterating and outputting the string. Our job is to include the line $counter++
inside the while
body to update $counter
and eventually stop the loop. Also, note that we are using a variable defined outside the loop, which is not usually the case with for
loops.
Beware of infinite loops! If the line $counter++
is omitted from the loop body, the expression $counter -lt 3
will always be true, and the loop will never terminate or iterate infinitely.
Instructions
Inside WHILE_Example.ps1, create a while
loop that will run as long as $count
is less than or equal to 30
.
Inside the body of the while
loop, increase the value of $count
by 3
.
Note: While giving this a try, you may cause an infinite loop. If this is the case, click refresh in your browser.
Inside the while
loop body, use Write-Host
to output $count
.
When complete, your program can now count by 3
. If you look at the last number in then series output, you might see 33
, or if you wrote the Write-Host
line before the $count
increment, you would see 30.
Incrementing the counter variable is important for loop termination, but where you place it within the loop body can also affect the outcome of the code.