for loops in Delphi
Orchard crates are counted upward, listed back downward, then walked without an index.
program ForLoops;
uses SysUtils;
const
Crates: array[0..3] of Integer = (14, 9, 22, 5);
var
Row, Total, Load: Integer;
begin
Total := 0;
for Row := 0 to High(Crates) do // to counts upward
Total := Total + Crates[Row];
WriteLn(Format('apples picked: %d', [Total]));
for Row := High(Crates) downto 0 do // downto counts backward
WriteLn(Format('crate %d holds %d', [Row, Crates[Row]]));
// for-in hands over each element, so no index is needed.
for Load in Crates do
Write(Load, ' ');
WriteLn;
end.
How it works
for Row := 0 to High(Crates) doadds every crate intoTotal.for Row := High(Crates) downto 0 doprints the same crates in reverse.for Load in Crates dohands over each element, so no subscript is needed.
Keywords and builtins used here
FormatHighIntegerWriteWriteLnarraybeginconstdodowntoendforinofprogramtousesvar
The run, in numbers
- Lines
- 19
- Characters to type
- 504
- Tokens
- 124
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 93 seconds.
Step 2 of 3 in Control flow, step 8 of 27 in Language basics.