Summary#
while repeats its body as long as the condition is true, checked before each pass — so a condition that is false
at the start means the body never runs. The condition must be a bool.
Signature#
while (<bool>) { … }Description#
while, foreach, or for — which loop?#
Use while when you do not know up front how many passes you need — consuming until something is exhausted,
converging on a value. When you are walking a collection, foreach says it better; when you
are counting, so does for.
int TimesToHalve(decimal amount, decimal limit) {
var steps = 0;
var current = amount;
while (current > limit) {
current = current / 2;
steps += 1;
}
return steps;
}Advance the condition, or it never ends#
The body must move the condition towards false. A while whose condition never changes is an infinite loop, and the
platform will not save you from it — it will simply run until it is stopped. Make the thing the condition reads the
thing the body changes, and keep them close enough to see together.
How do I stop part-way through?#
break leaves the loop; continue skips to the next check. See break / continue.
int CountUpTo(int limit) {
var i = 0;
while (true) {
i += 1;
if (i >= limit) { break; } // the exit is explicit, and easy to find
}
return i;
}See also#
- foreach — walking a collection
- for — a counted loop
- break / continue — leaving a loop, or skipping a pass