The reserved word while is used as a loop instruction where the test occurs before the loop is executed. It is a control construct that is similar to a {{HL|repeat}}-{{HL|until}} loop. Unlike for or repeat loops, while is the only type of loop where the loop might not be executed at all.
While shares a characteristic with for loops, in that the while ... do construct only covers a single statement. If more than one statement needs to be executed in the loop, a begin ... end block is required.
The while statement, in conjunction with {{HL|do}} repeats a statement as long as a condition evaluates to {{HL|true}}. The condition expression is evaluated prior to each iteration, determining whether the following block (or single statement) is to be executed. If the condition is false to begin with, the loop is never executed. This is the main difference from a repeat … until-loop, where the block is executed at least once, but succeeding iterations do not necessarily happen, though.
The following example contains unreachable code:
program whileFalse(input, output, stderr);
begin
while false do
begin
writeLn('never gets printed');
end;
end.
You usually use while-loops where, in contrast to {{HL|for}}, a running index variable is not required, the block executed can't be deduced from an index that's incremented by one, or to avoid a {{HL|break}} statement (which usually indicates bad programming style).
program whileDemo(input, output, stderr);
var
x: integer;
begin
x := 1;
// prints non-negative integer powers of two
while x < high(x) div 2 do
begin
writeLn(x);
inc(x, x); // x := x + x
end;
end.
see also
Keywords: begin — do — else — end — for — if — repeat — then — until — while