Loops
Loops are used when a block of code needs to executed several times. In Fortran, there are two basic types of loop: while loops and iterative loops. While loops continue to repeat indefinitely until some condition is satisfied, whereas iterative loops repeat the contained block of code a specified number of times. The following is an example of a while loop in Fortran:
-
program loop implicit none integer :: i,n i=1 n=5 exit ! 'exit' causes the loop to terminate write (*,*) i, i**2 i = i+1 ! Increment counter i by 1 if (i.gt.n) then ! if i > n then quit the loop endif do enddo end program loop
- Program Output:
-
1 1 2 4 3 9 4 16 5 25
An equivalent form of the above can written as:
-
program loop implicit none integer :: i,n n=5 i=1 write (*,*) i, i**2 i = i+1 !Increment counter i do while (i.le.n) ! Loop executes while i<=n enddo end program loop
For the other type of loop, the iterative loop, the number of times the loop will execute is known beforehand. This type of loop is written in Fortran as
-
Program loop implicit none integer :: i,n=5 do i=1,n,1 !Loop from i=1 to i=n in steps of 1 enddo end program loop
Each time the loop repeats, the index i increases by 1. This process is repeated until i reaches the maximum number of iterations n. This program produces the same output as the first two examples. In the first loop example above, the exitstatement was used when it was necessary to stop executing the code in the loop. cycle is another useful statement which may be used in do loops. When a cycle statement is encountered, the remaining code in the loop is skipped and the next loop iteration starts. For example:
-
program loop implicit none integer :: i,n=5 do i=1,n,1 ! Loop from i=1 to i=n in steps of 1 cycle ! Skip iteration 3 if (i .EQ. 3) endif write (*,*) i, i**2 enddo end program loop
Fortran also offers another looping construct for certain operations the implied loop. Implied loops are a shorthand way of looping over an index in read, write or array definition statements. The general form of an implied loop is:
( object , index = beginning , end , increment )
As in iterative loops, the increment is optional and may be omitted. As an example, the following code prints a list of integers from 1 to n.
write (∗,∗) (i, i=1,n)
Implied loops can only be used for the following:
- Read, write and print procedures
- Setting array elements
- Variable definition
In addition, implied loops cannot be nested, i.e. one cannot be placed inside another.