for
-loop syntax does not provide anything to change step amount from 1
to any other value.Integer
, the upper and lower values will be determined only once. Changes to such variables will have no effect on the loops iteration count.A for
loop iterates from the starting value to the ending value inclusive.
program SimpleForLoop;
{$APPTYPE CONSOLE}
var
i : Integer;
begin
for i := 1 to 10 do
WriteLn(i);
end.
Output:
1
2
3
4
5
6
7
8
9
10
The following iterates over the characters of the string s
. It works similarly for looping over the elements of an array or a set, so long as the type of the loop-control variable (c
, in this example) matches the element type of the value being iterated.
program ForLoopOnString;
{$APPTYPE CONSOLE}
var
s : string;
c : Char;
begin
s := 'Example';
for c in s do
WriteLn(c);
end.
Output:
E
x
a
m
p
l
e
A for
loop iterates from the starting value down to the ending value inclusive, as a "count-down" example.
program CountDown;
{$APPTYPE CONSOLE}
var
i : Integer;
begin
for i := 10 downto 0 do
WriteLn(i);
end.
Output:
10
9
8
7
6
5
4
3
2
1
0
A for
loop iterate through items in an enumeration
program EnumLoop;
uses
TypInfo;
type
TWeekdays = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);
var
wd : TWeekdays;
begin
for wd in TWeekdays do
WriteLn(GetEnumName(TypeInfo(TWeekdays), Ord(wd)));
end.
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
A for
loop iterate through items in an array
program ArrayLoop;
{$APPTYPE CONSOLE}
const a : array[1..3] of real = ( 1.1, 2.2, 3.3 );
var f : real;
begin
for f in a do
WriteLn( f );
end.
Output:
1,1
2,2
3,3