Loop Statements (for, while, repeat) |
Top Previous Next |
For, while, repeat statements
Loop statements are used to repeatedly execute code. You can use for/to statement to iterate from low to high bounds, for/downto to iterate in reverse order, or while or repeat statements to iterate with condition. Examples:
for i := 0 to 10 do ShowMessage(i);
for i := 10 downto 0 do ShowMessage(i);
i := 1; while i < 10 do begin ShowMessage(i); i := i * 2; end;
i := 1; repeat ShowMessage(i); i := i * 2;
Break and Continue
The Break intrinsic function can be used to break loop statement. Continue intrinsic function can be used to go to the next loop iteration. Using Break/Continue outside of the loop will raise run-time error.
i := 1; while i < 100 do begin if i = 15 then Break; i := F(i); end;
for i := 0 to 10 do begin if (i mod 2) <> 0 then Continue; ShowMessage(i + ' is an even number'); end;
The Break/Continue functions always works with innermost loop:
for i := 0 to 10 do // outer begin if i = 5 then Break; // Break outer loop.
for j := 0 to 10 do // inner begin if j = 5 then Break; // Break inner loop. end; end; |