When you want the behavior of a while
loop and would like 1 iteration to happen before any condition is checked, the do
…while
and do
…until
loops are a good choice.
$answer = 4 do { $input = Read-Host "Guess my number" } while ($input -ne $answer) Write-Host "Correct!"
The above example starts the loop with the keyword do
and the loop body will execute once. After one iteration, the condition $input -ne $answer
defined after the keyword while
will be checked. If the condition is true, the loop will continue.
The do
…while
allows Read-Host
to execute and set the value of $input
, which is then checked after the first loop. The output of the above example could look like this:
Guess my number: 5 Guess my number: 3 Guess my number: 4 Correct!
do
…until
is the same as do
…while
except when the condition is true, the loop will exit. The above example with a do
…until
will use the -eq
operator in the condition.
$answer = 4 do { $input = Read-Host "Guess my number" } until ($input -eq $answer) Write-Host "Correct!"
Remember that these loops are helpful when you want at least one loop iteration to happen, regardless of your code state.
Instructions
The file DO_Example.ps1 starts with 2 variables, $position
and $goal
. Your challenge is to create a do
…while
loop OR a do
…until
loop with the following characteristics:
- The loop should exit when
$position
equals$goal
using either the-eq
or-ne
operators. - The loop body should output the values of
$position
and$goal
using a singleWrite-Host
command. - The loop body should decrease the value of
$position
so the loop condition is met