Starts a loop that executes a finite number of times
1   for Variable := Integer Expression to|downto Integer Expression do Statement;
2   for Variable :=    Char Expression to|downto    Char Expression do Statement;
3   for Variable :=    Enum Expression to|downto    Enum Expression do Statement;
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.
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
 Author links

 Download this web site as a Windows program.

Example code : Integer for loop
  i : Integer;

  // Loop 5 times
  For i := 1 to (10 div 2) do
    ShowMessage('i = '+IntToStr(i));
Show full unit code
   i = 1
   i = 2
   i = 3
   i = 4
   i = 5
Example code : Character for loop
  c : char;
  // Loop 5 times - downwards
  For c := 'E' downto 'A' do
    ShowMessage('c = '+c);
Show full unit code
   c = E
   c = D
   c = C
   c = B
   c = A
Example code : Enumeration for loop
  suit : (Hearts, Clubs, Diamonds, Spades);
  // Loop 3 times
  For suit := Hearts to Diamonds do
    ShowMessage('Suit = '+IntToStr(Ord(suit)));
Show full unit code
   Suit = 0
   Suit = 1
   Suit = 2
Delphi Programming Neil Moffatt 2002 - 2020. All rights reserved.  |  Home Page