Revision 2 of 2, by WikiArchive on 11-9-2026. The page as it is now.
To
Back to Reserved words.
Keyword used to indicate the final value of the control value in a For loop, and that the loop is to increment the control variable by 1 on each loop. The value specified by TO should be greater than the initial value of the for loop.
For to do
var i : integer;
begin
for i := 1 to 10000 do
begin
//...
end;
end;The for to allow to execute code repeatedly for a fixed number of times.
Basic example
var
loopValue, startValue, endValue, resultValue: integer;
begin
startValue := 10;
endValue := 11;
resultValue := 0;
for loopValue := startValue to endValue do
begin
resultValue := loopValue + resultValue;
end;
end;The loop execute two times and variable resultValue value is 21.
Start and end value same
var
loopValue, startValue, endValue, resultValue: integer;
begin
startValue := 10;
endValue := 10;
resultValue := 0;
for loopValue := startValue to endValue do
begin
resultValue := loopValue + resultValue;
end;
end;The loop execute one time and variable resultValue value is 10.
Start value bigger than end value
var
loopValue, startNumber, endNumber, resultValue: integer;
begin
startValue := 10;
endValue := 9;
resultValue := 0;
for loopValue := startValue to endValue do
begin
resultValue := loopValue + resultValue;
end;
end;The loop execute none time and variable resultValue value is 0.
Note that the value of the "for loop variable" is undefined after a loop has completed or if a loop is not executed at all. However, if the loop was terminated prematurely with an exception or a break (or even a goto statement), the loop variable retains the value it had when the loop was exited.
Read more
From the Free Pascal wiki, page "To", as the Internet Archive kept it on 2024-09-20, last changed on 2024-08-15. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.
