Range Over Built in Co-array Fortran

Here we see how to iterate over elements in built-in data structures using DO loops and co-arrays. Let’s see how it works with some of the structures we’ve already learned.

program main
    implicit none
    
    ! Here we use DO loop to sum the numbers in an array.
    integer :: i, sum
    integer, dimension(3) :: nums = (/2, 3, 4/)

    sum = 0
    do i = 1, size(nums)
        sum = sum + nums(i)
    end do
    print *, "sum:", sum
    
    ! DO loop on arrays provides both the index and value for each entry.
    do i = 1, size(nums)
        if (nums(i) == 3) then
            print *, "index:", i
        end if
    end do
    
    ! DO loop on associative arrays (maps) to iterate over key/value pairs.
    type kv_pair
        character(len=:), allocatable :: key
        character(len=:), allocatable :: value
    end type kv_pair
    type(kv_pair), dimension(2) :: kvs

    kvs(1) = kv_pair("a", "apple")
    kvs(2) = kv_pair("b", "banana")

    do i = 1, size(kvs)
        print '(A, " -> ", A)', kvs(i)%key, kvs(i)%value
    end do
    
    ! DO loop can also iterate over just the keys of a map.
    do i = 1, size(kvs)
        print *, "key:", kvs(i)%key
    end do
    
    ! DO loop on strings to iterate over Unicode code points.
    character(len=2) :: str
    character(len=1) :: c

    str = "go"
    do i = 1, len(str)
        c = str(i:i)
        print *, i - 1, ichar(c)
    end do

end program main

To run the program, save the code in a file and execute it using Fortran:

$ gfortran -o main main.f90
$ ./main
 sum:                    9
 index:                  2
 a -> apple
 b -> banana
 key: a
 key: b
           0         103
           1         111

Now that we can run and build basic Fortran programs, let’s learn more about the language.