Choosing a Loop Structure
When presented with a problem that can be solved by using a looping structure the following rules should be applied:
- Loops which are to be executed a set number of times should normally be performed using the For structure. The following programs could be written using a For statement:
- Display the integer numbers 1 to 500.
- Get 50 numbers.
- Display all odd values between Start and Finish (where Start and Finish are integer variables).
- Loops which are executed an unknown number of times awaiting some event must use either While or Repeat. For example:
- Read in a set of values until a zero is entered.
- Perform an input of validation before the data is allowed to be processed by the main program.
When deciding between Repeat and While, keep in mind that the Repeat loop will execute at least once, whereas the While loop can execute zero times. The While loop typically exits when its condition is FALSE whereas the Repeat loop exits when its condition is TRUE.
Next: Example Loop Program