I’m new to Delphi so I apologize for the banality of my question.
How can I write in Delphi a for
loop with two counters like this in C++:
int i, j;
for (i=0, j=0; j<100; i++, j++) {
//do something
}
Thanks
You have to “unroll” the loop like this:
VAR I := 0;
FOR VAR J:=0 TO 99 DO BEGIN
// Do Something
INC(I)
END;
1
In Delphi, a for
loop can have only exactly one counter, and it can only step by 1. (It can, however, step either upwards, using to
, or downwards, using downto
.)
The other two loop constructs in the Delphi language are repeat
and while
.
With repeat
, your example could be written like this:
i := 0;
j := 0;
repeat
// Do something
Inc(i);
Inc(j);
until j = 100;
With while
, it could look like this:
i := 0;
j := 0;
while j < 100 do
begin
// Do something
Inc(i);
Inc(j);
end;
4