Range Over Built in Fortran

Iterating over elements in a variety of built-in data structures. Let’s see how to use loops with some of the data structures we’ve already learned.

PROGRAM RangeExample
    IMPLICIT NONE
    INTEGER :: i, n, sum
    INTEGER, DIMENSION(3) :: nums
    CHARACTER(LEN=5), DIMENSION(2) :: keys = (/ 'a', 'b' /)
    CHARACTER(LEN=10), DIMENSION(2) :: values = (/ 'apple', 'banana' /)
    CHARACTER(LEN=2), DIMENSION(2) :: str = 'go'
    
    ! Define nums array
    nums = (/ 2, 3, 4 /)
    sum = 0
    
    ! Calculate sum of array elements
    DO i = 1, SIZE(nums)
        sum = sum + nums(i)
    END DO
    
    PRINT *, 'sum: ', sum

    ! Print index where element is 3
    DO i = 1, SIZE(nums)
        IF (nums(i) == 3) PRINT *, 'index: ', i
    END DO

    ! Iterate over key-value pairs in parallel arrays
    DO i = 1, SIZE(keys)
        PRINT *, keys(i), ' -> ', values(i)
    END DO

    ! Print keys of the map
    DO i = 1, SIZE(keys)
        PRINT *, 'key: ', keys(i)
    END DO

    ! Iterate over characters of the string
    DO i = 1, LEN(str)
        PRINT *, 'Index: ', i-1, ' character: ', str(i:i)
    END DO

END PROGRAM RangeExample

Here we use a loop to sum the numbers in an array. Arrays work like this too.

    nums = (/ 2, 3, 4 /)
    sum = 0
    DO i = 1, SIZE(nums)
        sum = sum + nums(i)
    END DO
    PRINT *, 'sum: ', sum

Loop on arrays provides both the index and value for each entry. Above we didn’t need the index, so we didn’t use it explicitly. Sometimes we actually want the indexes though.

    DO i = 1, SIZE(nums)
        IF (nums(i) == 3) PRINT *, 'index: ', i
    END DO

Loop on arrays iterates over key-value pairs.

    DO i = 1, SIZE(keys)
        PRINT *, keys(i), ' -> ', values(i)
    END DO

A loop can also iterate over just the keys of an array.

    DO i = 1, SIZE(keys)
        PRINT *, 'key: ', keys(i)
    END DO

Loop on strings iterates over characters. The first value is the starting byte index of the character and the second the character itself.

    DO i = 1, LEN(str)
        PRINT *, 'Index: ', i-1, ' character: ', str(i:i)
    END DO

To run the program, you can use a Fortran compiler like gfortran.

$ gfortran -o RangeExample RangeExample.f90
$ ./RangeExample
 sum: 9
 index: 2
 a  -> apple
 b  -> banana
 key: a
 key: b
 Index: 0  character: g
 Index: 1  character: o