Description |
The For keyword starts a control loop, which is executed a finite number of times.
The Variable is set to the result of the 1st Expression. If the result is less than or equal to the result of the 2nd Expression (when to is specified), then the Statement is executed. Variable is then incremented by 1 and the process is repeated until the variable value exceeds the 2nd expression value.
For downto, the variable value is checked as being greater than or equal to the 2nd expression, and its value is decremented at the loop end.
The Expressions may result in any Ordinal type - Integers, Characters or Enumerations.
The Statement maybe a single line, or a set of statements with a begin/end block.
|
|
Notes |
The loop Variable value is not guaranteed by Delphi at loop end. So do not use it!
|
|
Related commands |
Begin |
|
Keyword that starts a statement block |
Do |
|
Defines the start of some controlled action |
DownTo |
|
Prefixes an decremental for loop target value |
End |
|
Keyword that terminates statement blocks |
Repeat |
|
Repeat statements until a ternmination condition is met |
To |
|
Prefixes an incremental for loop target value |
Until |
|
Ends a Repeat control loop |
While |
|
Repeat statements whilst a continuation condition is met |
|
|
|
Example code : Integer for loop |
var
i : Integer;
begin // Loop 5 times
For i := 1 to (10 div 2) do
WriteLn('i = '+IntToStr(i));
end;
|
Show full unit code |
i = 1
i = 2
i = 3
i = 4
i = 5
|
|
Example code : Character for loop |
var
c : char;
begin // Loop 5 times - downwards
For c := 'E' downto 'A' do
WriteLn('c = '+c);
end;
|
Show full unit code |
c = E
c = D
c = C
c = B
c = A
|
|
Example code : Enumeration for loop |
var
suit : (Hearts, Clubs, Diamonds, Spades);
begin // Loop 3 times
For suit := Hearts to Diamonds do
WriteLn('Suit = '+IntToStr(Ord(suit)));
end;
|
Show full unit code |
Suit = 0
Suit = 1
Suit = 2
|
|