DelphiBasics
For
Keyword
Starts a loop that executes a finite number of times
1 keyword For(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;
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
BeginKeyword that starts a statement block
DoDefines the start of some controlled action
DownToPrefixes an decremental for loop target value
EndKeyword that terminates statement blocks
RepeatRepeat statements until a ternmination condition is met
ToPrefixes an incremental for loop target value
UntilEnds a Repeat control loop
WhileRepeat statements whilst a continuation condition is met
 Download this web site as a Windows program.




 
Example code : Integer for loop
var
  i : Integer;

begin
  // Loop 5 times
  For i := 1 to (10 div 2) do
    ShowMessage('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
    ShowMessage('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
    ShowMessage('Suit = '+IntToStr(Ord(suit)));
end;
Show full unit code
  Suit = 0
  Suit = 1
  Suit = 2
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page