Arrays
An array is an indexed group of variables of the same type that are referred to by a single name. Arrays are useful for storing lists of related data. The individual elements of an array are accessed by using a subscript. The following Fortran example illustrates how to declare a 1D array with 3 entries and set each of its elements to zero:
-
integer :: i real :: a(3) ! A 1D array with 3 entries do i = 1,3 ! Loop over each entry and set to zero a(i) = 0.0 enddo
To define a 2D array with 3 rows and 3 columns and set all of its elements to zero:
-
a(i,j) = 0.0 ! A 2D array with 3 rows and 3 columns real :: a(3,3) ! Loop over each entry and set to zero do i = 1,3 ! Loop over rows do j = 1,3 ! Loop over each column within the row enddo enddo
Arrays in Fortran can have a maximum of 7 dimensions. In most practical applications, the dimensions of an array will not be known before the program is run. If the array is used for storing a matrix for example, the dimensions of the matrix will probably vary from problem to problem. For this reason, it is possible to define dynamic arrays whose dimensions can be set or change while the program is running. This accomplished in Fortran as follows:
-
write (*,*) 'Error in memory allocation' exit matrix(j,i) = 0.0< do j=1,rows enddo deallocate(matrix) program dynamic implicit none real, allocatable :: matrix(:,:) ! Matrix is dynamic - will specify size below integer :: components integer :: rows, cols integer :: info integer :: i,j rows = 3 cols = 3 ! Allocate the required memory for this matrix allocate(matrix(rows,cols),stat=info) < ! Check status of allocation: Error if info not ! equal to 0 if (info .NE. 0) then endif ! Initialise all matrix elements to zero do i=1,cols enddo ! Perform other computations here... ! Deallocate matrix - return memory to system ! First check if memory has been allocated to ! matrix if (allocated(matrix)) then endif end program dynamic
The status of allocate() should always be checked to ensure that the memory has been successfully allocated. Memory allocation can fail if for example an attempt is made to allocate more memory than is available on the system. In addition, allocated memory should always be deallocated so that the memory is returned to the system.