Loops

FORTRAN also has a way to repeat a portion of the program statements. For this lesson, we will discuss a variety of common loop syntaxes used in FORTRAN. A common operation that requires a loop, is how to perform some operation on each element of an array. Review the Arrays lesson first to get the most out of this lesson.

The most basic loop uses a GOTO label statement and has the meaning, "if condtion condition is true, execute statements, then GOTO label to repeat the test and statements. Label is the label number of the IF () THEN line of code. When the condition is false, program execution skips to the ENDIF line and continues with the rest of the program.

 c23456789012345678901234567890123456789012345678901234567890123456789012
   10  IF (condition)
          statement x  % body of while loop
          statement y
          statement z
          GOTO 10
       ENDIF

CAUTION: Poor use of GOTO statements, like using a GOTO statement that goes to a different place in the program can lead to much confusion. Code that has many GOTO statements that are hard to follow is known as "spaghetti code" because it is extremely hard to follow any path of execution through the program.

If we know how many times a loop is going to execute, it is preferred that we write it as a DO loop. The DO loop allows us to specify an initial value for the loop counter, and end value for the loop counter, and an increment value for the loop counter.

A simple DO loop that repeats 10 times might look like this:

 c23456789012345678901234567890123456789012345678901234567890123456789012
       DO 10 i = 1, 10
          statement x  % body of while loop
          statement y
          statement z
   10  CONTINUE

A more general form for the DO is:

 c23456789012345678901234567890123456789012345678901234567890123456789012
       integer i, initval, endval, incrval
       intival = 1
       endval  = 20
       incrval = 2
       DO 100 i = initval, endval, incrval
          statement x  % body of while loop
          statement y
          statement z
   100 CONTINUE

Some FORTRAN compilers also support a WHILE loop syntax with this form:

 c23456789012345678901234567890123456789012345678901234567890123456789012
       WHILE (condition) DO
          statement x  % body of while loop
          statement y
          statement z
          update condition variable(s) in some way
       ENDDO

or a DO WHILE loop with this syntax:

 c23456789012345678901234567890123456789012345678901234567890123456789012
       DO WHILE (condition) 
          statement x  % body of while loop
          statement y
          statement z
          update condition variable(s) in some way
       ENDDO

CAUTION: The above syntax can often lead to infinite loops, should the programmer forget to update one of the condition variables within the loop statements.