Arrays in Fortran

In Fortran, an array is a numbered sequence of elements of a specific type and shape. Arrays are fundamental in Fortran and are used extensively in scientific and numerical computing.

program arrays
  implicit none
  
  ! Here we create an array 'a' that will hold exactly 5 integers.
  ! By default, an array is uninitialized in Fortran.
  integer, dimension(5) :: a
  integer, dimension(5) :: b
  integer, dimension(2,3) :: twoD
  integer :: i, j

  ! Print the uninitialized array
  print *, "emp:", a

  ! We can set a value at an index using the array(index) = value syntax
  a(5) = 100
  print *, "set:", a
  print *, "get:", a(5)

  ! The intrinsic function 'size' returns the size of an array
  print *, "len:", size(a)

  ! Use this syntax to declare and initialize an array in one line
  b = [1, 2, 3, 4, 5]
  print *, "dcl:", b

  ! In Fortran, you can't use '...' to let the compiler count elements
  ! But you can use implied-do loops for initialization
  b = [(i, i=1,5)]
  print *, "dcl:", b

  ! In Fortran, you can't specify non-contiguous indices during initialization
  ! But you can assign values individually
  b = 0
  b(1) = 100
  b(4) = 400
  b(5) = 500
  print *, "idx:", b

  ! Array types are multi-dimensional by default in Fortran
  do i = 1, 2
    do j = 1, 3
      twoD(i,j) = i + j - 2
    end do
  end do
  print *, "2d: ", twoD

  ! You can create and initialize multi-dimensional arrays at once too
  twoD = reshape([1, 2, 3, 1, 2, 3], [2, 3])
  print *, "2d: ", twoD

end program arrays

Note that arrays in Fortran are printed in a different format compared to some other languages. When using the simple print * statement, they are typically printed as a space-separated list of values.

To compile and run this Fortran program:

$ gfortran arrays.f90 -o arrays
$ ./arrays
 emp:           0           0           0           0           0
 set:           0           0           0           0         100
 get:         100
 len:           5
 dcl:           1           2           3           4           5
 dcl:           1           2           3           4           5
 idx:         100           0           0         400         500
 2d:            0           1           2           1           2           3
 2d:            1           2           3           1           2           3

Fortran arrays have some key differences from arrays in other languages:

  1. Fortran arrays are 1-indexed by default, unlike many other languages which are 0-indexed.
  2. Fortran supports multi-dimensional arrays natively, without need for array of arrays.
  3. Fortran allows for more flexible array indexing and slicing operations.
  4. Fortran arrays can have user-defined lower and upper bounds for each dimension.

These features make Fortran particularly well-suited for scientific and numerical computing tasks involving complex array operations.