Arrays

Declare shape

An array declaration states the element type and the size in each dimension inside parentheses.

A one dimensional array is a list, while a two dimensional array is a table with rows and columns.

program shapedemo implicit none real :: v(5) real :: grid(3, 4) print *, size(v) print *, size(grid) end program shapedemo

1-based indexing

By default the first element is number 1, the second is number 2, and so on up to the declared size.

A loop from 1 to size walks the whole array safely without touching memory outside it.

program indexdemo implicit none integer :: v(3) integer :: i v(1) = 10 v(2) = 20 v(3) = 30 do i = 1, 3 print *, i, v(i) end do end program indexdemo

Initialize

Arrays can start with one shared value or with an explicit list in square brackets.

The bracket form lists elements in index order and must hold exactly as many values as the array size.

program initdemo implicit none real :: a(3) = 0.0 integer :: b(3) = [1, 2, 3] print *, a print *, b end program initdemo

Whole-array ops

Fortran applies arithmetic to whole arrays at once, with no loop needed for simple element by element math.

Intrinsics such as sum then reduce the array to one answer in a single call.

program wholedemo implicit none real :: a(3) = [1.0, 2.0, 3.0] real :: b(3) b = a * 2.0 + 1.0 print *, b print *, sum(b) end program wholedemo

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev