In the
curly brace family of programming languages, ie
C and derived languages, c-style for loops are Ubiquitous. For loops in these languages are the
swiss army chainsaw of looping. They'll do anything if you set it up right.
For loops in Pascal are less flexible than this in some ways and more flexible in others. Pascal style for loops are only for for repeating yourself a fixed number of times.
In the following, I will be showing code for Delphi, the most common pascal variant in use from the late 1990s. Your millage may vary in other pascals.
Pascal for loops always increment or decrement an index variable, whcih must be pre-declared like all others. The most restrictive scope to which you can declare this variable is the enclosing procedure or function.
var
iLoop: integer;
begin
for iLoop := 1 to 100 do
begin
// this happens 100 times
end;
for iLoop := 100 downto 1 do
begin
// this happens 100 times, reverse order
end;
Unlike a while or repeat loop, the bounds are evaluated once only – they are not tested at the end of each iteration. So if you code
var
iLoop: integer;
begin
for liLoop := GetMin() to GetMax() do
begin
// changes here to the result of GetMin() and GetMax() have no effect on the looping
end;
end;
Flow of control with the loop can be changed with the break statement, which exits the loop, or the continue statement, which ends the current iteration and continues with the next one. Note that neither of these are in the original pascal specification. However life without them would be annoying.
Pascal’s most fun for-loop feature is that the loop index need not be an integer, it can be any ordinal type. You can loop over char, an enum or over boolean (with a grand total of two possible values). Here's an example for looping over an enum:
type
TCardSuit = (csHearts, csClubs, csDiamonds, csSpades);
var
SuitLoop: TcardSuit;
begin
for suitLoop := Low(TCardSuit) to High(TcardSuit) do
begin
// do something with the suit
...
end;
end;
In recent times the foreach loop in languages such as PHP and C# has taken over some of the simpler tasks of for loops, by iterating over all elements in a list or collection with even less effort.