For in Co-array Fortran

Co-array 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 do 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 run indefinitely until you exit.
  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 that supports Co-array features:

$ gfortran -coarray=single for_example.f90 -o for_example
$ ./for_example

The output will be:

           1
           2
           3
           0
           1
           2
 range           0
 range           1
 range           2
 loop
           1
           3
           5

In Co-array Fortran:

  1. The do while loop is used for condition-based looping.
  2. The traditional do loop is used for counted iterations.
  3. There’s no direct equivalent to Go’s range, but we can use a regular do loop to achieve similar functionality.
  4. An infinite loop can be created with a simple do without conditions.
  5. exit is used to break out of a loop (equivalent to Go’s break).
  6. cycle is used to skip to the next iteration (equivalent to Go’s continue).

Note that Co-array Fortran, being an extension of Fortran, follows Fortran’s syntax and conventions. The structure of the program and the way loops are implemented differ significantly from Go, but the core concepts of iteration and flow control remain similar.