DELPHI: Repetition (loops)
 

Loops are used for repetition of certain statements for a set number of times or according to a certain condition.

FOR loop (unconditional loop)

  • Repeat instructions for a set number of times.

  • Uses a counter (must be ordinal: integer or char)

  • Uses a start and ending value that determines repetitions.

  • Can count/move up (e.g. 1 TO 10) or down (10 DOWNTO 1).

  • Structure:

    FOR <counter> := <start value> TO <ending value> DO
    BEGIN
     <statements;>
    END;

     

WHILE loop (conditional loop)

  • Repeats depending on a certain condition(s).

  • Repeats while a certain condition is TRUE.

  • ITC:
    - Variable tested at beginning of loop must have initial value.
    - Variable is tested at the beginning of loop.
    - Variable must change in order for loop to stop.

  • Structure:

    WHILE <condition(s)> DO
    BEGIN
     <statement(s)>
     <change condition to stop loop>
    END;


REPEAT loop (conditional loop)

  • Repeats depending on a certain condition(s).

  • Unlike the WHILE loop the REPEAT loop tests for a condition at the end of executing certain statements rather than before.

  • Instructions in a REPEAT loop will always be executed at least once.

  • Does not need a BEGIN and END.

  • The condition(s) indicate when to stop not when to go on as with the WHILE.

  • ICT
    - Variables to be tested must be initialized before execution.
    - Variable must be changed at the end of loop to avoid an infinite loop (loop will never stop repeating)
    - Variable is tested at the end of the loop. If the statement is FALSE then the loop will be repeated again.

  • Structure:

    REPEAT
     <statement(s)>
     <change condition to stop loop>
    UNTIL <conditions to stop>;

     

Return to Delphi resources index




Return to Home Page

2024 J Olivier. Except where otherwise noted, the content on this website is licensed under the terms of the Creative Commons BY SA 4.0 license. https://creativecommons.org/about/cclicenses/