When you want the behavior of a while loop and would like 1 iteration to happen before any condition is checked, the dowhile and dountil 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 dowhile 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!

dountil is the same as dowhile except when the condition is true, the loop will exit. The above example with a dountil 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.



The file DO_Example.ps1 starts with 2 variables, $position and $goal. Your challenge is to create a dowhile loop OR a dountil 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 single Write-Host command.
  • The loop body should decrease the value of $position so the loop condition is met

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?