While

While

While[ cond ] ... End executes a script block repeatedly, as long as a condition holds.

Usages

While[ cond ] ... End

Checks cond, and if it is not False, executes the script between While and End. This is repeated until cond is False. If cond is False at the start, the block is never executed. As in If, comparisons such as < are evaluated in the condition.

Example in out
Count to 10. ii := 0
While[ii < 10]
  ii := CalcPlus[ii, 1]
End
ii = 10
The condition is False at the start, so the block is not executed. ii := 20
While[ii < 10]
  ii := CalcPlus[ii, 1]
End
ii = 20
Multiply by random numbers until the product is at least 100. total := 1
While[total < 100]
  total := CalcTimes[total, RandomInt[{2, 9}]]
End
for example total = 189
Choose a new random number until it differs from x. x := RandomInt[{1, 10}]
y := RandomInt[{1, 10}]
While[x == y]
  y := RandomInt[{1, 10}]
End
for example x = 3
y = 7
Details
  • Number of iterations: the block can be executed at most 101 times. If the condition still holds after that, the script stops with an error.
Warning

Make sure the condition becomes False. A condition that cannot be decided, such as y < 10 when y has no value, is treated as True, so the loop never ends and the script stops with an error after 101 iterations. Use Strict if the condition may be undecided: While[Strict[y < 10]].

See also: For, If, Strict