Choosing a Loop Structure Review

When presented with a problem, which can be solved using a looping structure the following rules should be applied:

1) Loops which are to be executed a set number of times should normally be performed using a for loop.  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).

2) Loops which are executed an UNKNOWN number of times awaiting some event must use either while do or do while. 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 do while and while do, keep in mind that the do while loop will execute at least once, whereas the while do loop could possibly execute zero times, and typically the while do loop exits when its condition is ‘false’ whereas the do while loop exits when its condition is ‘true’.

Next: Iteration Challenges