Playing with arrays in Fortran (Part 2)

the saga continues…

Array constructors

Assigning values to an array can be done in a number of ways. The first is the traditional technique using loops. The second uses an array constructor of the form:

real, dimension(3) :: a
a = (/ 0.2, 0.4, 0.8 /)

Variable dimensions

There is also the notion of variable-dimension array arguments in subroutines, which makes it possible to write generic routines without explicitly specifying array dimensions passed to them.

subroutine SubX(N)

  integer, intent (in) :: N
  real, dimension (N) :: arrY

end subroutine SubX

Fortran can automatically create arrays just with declarations on entry to subroutines, as long as the the dimensions are known at run time … this doesn’t require the dimensions to be declared parameter attribute, they can be arguments, e.g.,


Fortran 90 added support for array notation that allows operations on array sections, the use of vector indices, and the ability to perform array slicing. Here is an example:

program sliceArray
  implicit none
  integer, dimension(20,20) :: theArray
  integer :: i, j

  theArray = 0
  theArray(7:14,7:14) = 1

  do i = 1,20
    do j = 1,20
      write(*,"(I2)",advance="no") theArray(i,j)
    end do
  end do

end program sliceArray

Here a 20×20 array is created, and all elements are set to zero. Next a square slice comprising 8×8 elements in the centre is set to 1. Easy!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s