Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Arrays and Numerics

Arrays: The Basics

Learn Fortran arrays from scratch: declaring 1D and 2D arrays, custom lower bounds, array constructors, implied do loops, column-major storage, size, shape and reshape.

Arrays are the heart of Fortran. The language was built to process tables of numbers, and its array features are still among the best of any language: arrays carry their shape with them, can be indexed from any starting number, and can be added, multiplied and passed to functions as whole objects. This lesson covers declaration, indexing, initialization and memory layout.

Declaring an array

An array is a named collection of elements of one type. Give it a size in parentheses after the name, or with the dimension attribute:

FORTRAN
program array_decl
  implicit none
  real :: temps(7)                      ! 7 reals
  integer, dimension(5) :: counts      ! 5 integers
  logical :: flags(3)
  character(len=8) :: names(4)         ! 4 strings of length 8
  integer :: i

  temps = 0.0                          ! set every element
  do i = 1, 5
    counts(i) = i * 10
  end do
  print *, counts
end program array_decl

Elements are written name(index), with parentheses (not square brackets). By default the first element is counts(1): Fortran arrays are one-based. The program prints 10 20 30 40 50 (list-directed, each number preceded by spaces).

Choosing your own bounds

You are not limited to starting at 1. Write lower:upper:

FORTRAN
real :: y(0:9)            ! indices 0..9, ten elements
integer :: year(1990:2025)  ! 36 elements, one per year
real :: w(-2:2)           ! indices -2, -1, 0, 1, 2

year(2000) is simply the value for the year 2000: no subtracting offsets. This makes translating math (which often uses 0-based or negative indices) very natural.

Python Stand-in (Python): an array with custom bounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Array constructors

Create an array value with [ ... ] (older code writes (/ ... /)):

FORTRAN
integer :: a(5) = [10, 20, 30, 40, 50]
real, parameter :: weights(3) = [0.2, 0.3, 0.5]
integer :: squares(10)

squares = [(i * i, i = 1, 10)]     ! implied do inside the constructor

All elements of a constructor must have the same type (and, for strings, the same length, unless you write a type: [character(len=5) :: "a", "bcd"]). Constructors build values on the fly, so you can pass them to procedures: print *, sum([1, 2, 3]).

For a constant table, combine parameter with a constructor. The compiler then knows the values at compile time.

Bounds and shape: size, lbound, ubound

Arrays know their own size. Never hard-code a length twice; ask the array:

Function Meaning For real :: y(0:9)
size(y) number of elements 10
lbound(y, 1) lower bound 0
ubound(y, 1) upper bound 9
rank(y) number of dimensions (2018) 1
shape(y) extents as an array [10]
FORTRAN
do i = lbound(y, 1), ubound(y, 1)
  y(i) = real(i) ** 2
end do

Two and more dimensions

A matrix has two indices, row first:

FORTRAN
program matrix_demo
  implicit none
  integer :: m(3, 4)           ! 3 rows, 4 columns
  integer :: i, j

  do j = 1, 4
    do i = 1, 3
      m(i, j) = 10 * i + j
    end do
  end do
  print *, m(2, 3)              ! 23
  print *, shape(m)             ! 3 4
  print *, size(m)              ! 12
end program matrix_demo

Fortran allows up to 15 dimensions (7 before 2008). m(2, 3) is row 2, column 3.

Column-major order

Memory is one long line. Fortran stores matrices column by column: the first index changes fastest. For m(3, 4) the elements sit in memory like this:

flowchart LR
  A["m(1,1)"] --> B["m(2,1)"] --> C["m(3,1)"] --> D["m(1,2)"] --> E["m(2,2)"] --> F["m(3,2)"] --> G["m(1,3)"]

The first index varies fastest, so the first column comes first in memory.

This matters for speed. A loop is fastest when the innermost loop runs over the first index, because it walks consecutive memory:

FORTRAN
do j = 1, n          ! outer loop: columns
  do i = 1, n        ! inner loop: rows, contiguous in memory
    a(i, j) = a(i, j) * 2.0
  end do
end do

Swapping the loops works, but is often several times slower on large arrays. C and Python (NumPy default) use the opposite, row-major, order.

Python Stand-in (Python): column-major memory order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

reshape

reshape(source, shape) turns a flat list into a matrix, filling column by column:

FORTRAN
integer :: m(2, 3)
m = reshape([1, 2, 3, 4, 5, 6], [2, 3])
! m(1,:) = 1 3 5
! m(2,:) = 2 4 6

If you want to type the matrix row by row, use order=[2, 1] or transpose the result:

FORTRAN
m = reshape([1, 2, 3, 4, 5, 6], [2, 3], order=[2, 1])
! m(1,:) = 1 2 3
! m(2,:) = 4 5 6
Python Stand-in (Python): reshape fills columns first

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Out-of-bounds access

Using an index outside the declared bounds is an error, but by default the compiler does not check, so the program may silently read or overwrite other memory. During development compile with -fcheck=bounds (or -fcheck=all), and the program stops with a message such as Index '8' of dimension 1 of array 'a' above upper bound of 5. Remove the checks only for final timing runs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does real :: v(0:4) declare?

    The bounds 0:4 give five elements with indices 0, 1, 2, 3 and 4.
  2. 2. What is stored in memory first for the matrix m(3, 4)?

    Fortran is column-major, so the first index varies fastest and column 1 comes first in memory.
  3. 3. Which loop order is fastest for a(i, j)?

    The inner loop should run over the first index, which is contiguous in memory.
  4. 4. What does shape(m) return for integer :: m(3, 4)?

    shape returns an array holding the extent of each dimension: 3 and 4.

Summary

  • Declare arrays with type :: name(size) or dimension; indexing uses parentheses and starts at 1 unless you write lower:upper.
  • Constructors [1, 2, 3] and implied do loops create array values.
  • size, lbound, ubound, shape and rank describe an array, so you never repeat a length.
  • Arrays are stored column-major; keep the first index in the innermost loop.
  • reshape builds matrices; compile with -fcheck=bounds while developing.

Next: Array Sections and Whole-Array Operations