Next: The Power of Looping
Up: DO Loop Basics
Previous: DO Loop Basics

Why DO Loops?

When writing a Fortran program, it is very common to want to do the same thing over and over again. Coding this repetition into a program can make the program very long and unwieldy. To see what I mean, take a look at ``loop1.f'' in your ``examples'' directory (or view it directly).

Where in this program are we repeating something over and over?

Click here for the answer

Actually, we aren't repeating exactly the same thing over and over. What is different about each ``repetition''?

Click here for the answer

We can use a DO loop to simplify this program if we can make each repetition be exactly the same. Can you think of a way of modifying the program so that each of the six repetitions is exactly the same, without changing what the user sees?

Click here for the answer

To see an example of this idea in action, look at ``loop2.f'' (or view it directly).

Notice that this program is actually quite a bit longer than the original. Nevertheless, we have succeeded in making each of the six repetitions exactly the same! In each, we print a message, read a value into X, and add X into the current value of SUM. Notice that we had to be careful to initialize the value of SUM before the repetitions began and we had to change the PRINT statement that follows the repetition.

Once you have found a way to make each repetition identical, it is a simple matter to use a DO loop to drastically shorten the program. Take a look at ``loop3.f'' (or view it directly) to see how.

Notice what I have done. The sequence of statements that was previously repeated six times now appears as the body of the DO loop. The loop executes six times, as the value of I counts up from 1 to 6. The effect observed by the user is completely unchanged. Run the three versions of the program to convince yourself of that.


Next: The Power of Looping
Up: DO Loop Basics
Previous: DO Loop Basics

Hamlet Project
hamlet@cs.utah.edu