Title here
Summary here
Pascal provides several looping constructs. Here are some basic types of loops.
program ForLoops;
uses
SysUtils;
var
i, j, n: Integer;
begin
// The most basic type, with a single condition.
i := 1;
while i <= 3 do
begin
WriteLn(i);
i := i + 1;
end;
// A classic initial/condition/after for loop.
for j := 0 to 2 do
begin
WriteLn(j);
end;
// Pascal doesn't have a direct equivalent to Go's range over an integer,
// but we can simulate it with a for loop.
for i := 0 to 2 do
begin
WriteLn('range ', i);
end;
// A repeat-until loop will execute at least once.
repeat
WriteLn('loop');
until True;
// You can also continue to the next iteration of the loop.
for n := 0 to 5 do
begin
if n mod 2 = 0 then
continue;
WriteLn(n);
end;
end.
To run the program, save it as forloops.pas
and use the Pascal compiler (e.g., Free Pascal):
$ fpc forloops.pas
$ ./forloops
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
Pascal’s looping constructs are slightly different from some other languages:
while
loop is used for condition-based loops.for
loop in Pascal is typically used for counting loops with a known range.for
without condition, but you can use while True
for an infinite loop.repeat-until
loop is similar to a do-while
loop in other languages, always executing at least once.continue
to skip to the next iteration, similar to many other languages.We’ll see some other loop forms later when we look at arrays, strings, and other data structures.