While: Difference between revisions
(resolve language imprecision) |
No edit summary |
||
Line 33: | Line 33: | ||
end; | end; | ||
end. | end. | ||
</syntaxhighlight> | |||
You can use <syntaxhighlight lang="pascal" inline>Continue</syntaxhighlight> to jump to the end of the loop. | |||
In the example below all values from 1 to 10 are printed, except 5. | |||
<syntaxhighlight lang="pascal" line highlight="9"> | |||
program whileDemo(input, output, stderr); | |||
var | |||
i:integer=0; | |||
begin | |||
while true do | |||
begin | |||
inc(i); | |||
if i>10 then break; | |||
if i=5 then continue; | |||
writeLn(i); | |||
end; | |||
end; | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 09:54, 4 January 2023
│
Deutsch (de) │
English (en) │
suomi (fi) │
français (fr) │
русский (ru) │
while
in conjunction with do
repeats a statement as long as a condition evaluates to true
.
The condition expression is evaluated prior each iteration, determining whether the following statement is executed.
This is the main difference to a repeat … until
-loop, where the loop body is executed at any rate, 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 for
-loops, a running index variable is not required, the statement executed can't be deduced from an index that's incremented by one, or to avoid a 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.
You can use Continue
to jump to the end of the loop.
In the example below all values from 1 to 10 are printed, except 5.
program whileDemo(input, output, stderr);
var
i:integer=0;
begin
while true do
begin
inc(i);
if i>10 then break;
if i=5 then continue;
writeLn(i);
end;
end;
see also
Keywords: begin — do — else — end — for — if — repeat — then — until — while