You've now seen a number of examples of loops in action. More practice will help you recognize the possibilities inherent in looping. In the meantime, let's look in more detail at the rules that govern how loops operate.
Take a look at ``looptest.f'' in your ``examples'' directory (or view it directly). This program does nothing but illustrate how a DO loop can be used to step through a sequence of values for a variable.
Notice that it asks the programmer for values for ``FIRST'', ``LAST'', and ``STEP'', which are used to control the loop. It prints out the value of the loop variable ``I'' during each iteration, and the value when the loop terminates. You should use this program to experiment with different values for ``FIRST'', ``LAST'', and ``STEP''. Try to predict what will happen, then try it out and see. Here are some sample values to try:
FIRST = 1, LAST = 10, STEP = 1 FIRST = 1, LAST = 10, STEP = 2 FIRST = 1, LAST = 1, STEP = 1 FIRST = 10, LAST = 1, STEP = -1 FIRST = 10, LAST = 1, STEP = -3 FIRST = 1, LAST = 10, STEP = -1 FIRST = 1, LAST = 0, STEP = 1 FIRST = 1, LAST = 10, STEP = 0
The last example is revealing. Don't try to use a STEP of 0 or strange things will happen. (What happened is that the computer tried to divide by zero to figure out how many iterations to perform!)
If you haven't gotten the idea yet, try a few more examples of your own choosing. (By the way---the loop control variables don't have to be called FIRST, LAST, and STEP. We've just chosen those names here. In fact, they don't even have to be variables. As you have seen, they just need to be expressions that evaluate to numbers.)
Hamlet Project