Choosing loops and decision structures
Control flow and strings · about 7 min
Use FOR when the required index range is known in advance. A WHILE loop checks its condition before running, so its body can execute zero times. REPEAT checks after the body and therefore executes at least once; it stops when its UNTIL condition becomes true. Every condition-controlled loop needs a change that moves it towards termination.
A nested loop completes the inner loop for each outer iteration. For a rectangular grid, the outer index often represents a row and the inner index a column. Reset row-specific accumulators inside the outer loop but before the inner loop. Use IF for conditions involving ranges or combinations; CASE is useful for discrete ordinal choices. Check thresholds from most restrictive to least restrictive when overlapping conditions are tested in an IF/ELSE chain.
Key points- Choose FOR, WHILE or REPEAT for a reason.
- Trace nested loops.
- Avoid non-terminating repetition.
Worked example: // iRow, iCol: Integer; sLine: string; redOutput: TRichEdit redOutput.Clear; for iRow := 1 to 3 do begin sLine := ''; for iCol := 1 to iRow do sLine := sLine + '*'; redOutput.Lines.Add(sLine); end; The output has one, two and three stars on separate lines. The inner body executes 1+2+3=6 times. Resetting sLine before the outer loop instead would retain earlier rows and produce the wrong pattern.
WHILE continues while its condition is true; REPEAT stops when its condition becomes true. Swapping these conditions can reverse the intended behaviour.
Practice: Write the inner and outer bounds for a rectangle with 4 rows and 6 stars per row. How many stars are appended?
Answer: Outer loop 1 to 4; inner loop 1 to 6. Reset the line for each row and append it after the inner loop. There are 24 star appends and 4 output lines.
Recap: Choose a loop from its start, bounds and stopping rule; place resets at the correct nesting level.