Modules Fortran

Modules are program units which contain both the data and subprograms associated with a certain task. An example, shown below, is a vector module. This module defines a user type (vectorType) containing three variables: the number of components, the vector itself and the vector

integer :: n=3
real :: a(3) ! The vector components
real :: magnitude ! The vector magnitude
x%magnitude = x%magnitude + x%a(i)*x%a(i)
type(vectorType), intent(inout) :: x
integer :: i
x%magnitude = 0.0
do i = 1,x%n
enddo

x%magnitude = sqrt(x%magnitude)
module vector
implicit none
private

        ! private statement causes all data and
        ! subprograms to be hidden from calling
        ! program, unless otherwise specified
        ! Create a new type which will be visible to
        ! the calling program
type,public :: vectorType

! The number of components in the vector
end type vectorType

! Make subroutine magnitude public, i.e. visible
! to calling program:
public :: magnitude
contains
subroutine magnitude (x)
end subroutine magnitude
end module vector magnitude

A function is then defined which computes the magnitude of the array. Additional functionality could be added by including subprograms which compute the dot product of two vectors for example.

The module may be used in a program as follows:

program vectorTest

! make the data and functions in vector module
! available to this program
use vector
implicit none

! Create a new vector
type(vectorType) :: v1

! Set some test values
v1%a(1) = 1.0; v1%a(2) = 1.0; v1%a(3) = 0.0

! Compute the magnitude of v1.
call magnitude(v1)
write (*,*) 'Vector Magnitude:'
write (*,*) (v1%magnitude)
end program vectorTest
Program Output:
Vector Magnitude:
  1.4142135

Supported By

File Browser Reference
Department FHERIS
University of Galway
HEA Logo