For in Fortran

Fortran provides several looping constructs. Here are some basic types of loops.

program main
    implicit none
    integer :: i, j, n

    ! The most basic type, with a single condition.
    i = 1
    do while (i <= 3)
        print *, i
        i = i + 1
    end do

    ! A classic initial/condition/after loop.
    do j = 0, 2
        print *, j
    end do

    ! Another way of accomplishing the basic "do this N times" iteration.
    do i = 0, 2
        print *, "range", i
    end do

    ! A loop without a condition will loop repeatedly
    ! until you exit the loop or return from the enclosing subroutine.
    do
        print *, "loop"
        exit
    end do

    ! You can also cycle to the next iteration of the loop.
    do n = 0, 5
        if (mod(n, 2) == 0) then
            cycle
        end if
        print *, n
    end do

end program main

To run the program, save it as for_example.f90 and compile it using a Fortran compiler, then run the executable:

$ gfortran for_example.f90 -o for_example
$ ./for_example
           1
           2
           3
           0
           1
           2
range           0
range           1
range           2
loop
           1
           3
           5

In Fortran:

  • The do statement is used for loops.
  • do while is used for condition-based loops.
  • A simple do with start and end values is used for counting loops.
  • exit is used to break out of a loop (equivalent to break in other languages).
  • cycle is used to continue to the next iteration (equivalent to continue in other languages).

We’ll see some other loop forms later when we look at array operations and other data structures.