Subprograms, functions and subroutines
In the design of larger programs, the typical approach is to divide the program into several smaller, more manageable tasks. In Fortran and other programming languages, this corresponds to creating a set of subprograms. The two basic types of subprograms in Fortran are functions and subroutines. Variables declared within a function or subroutine are usually local, i.e. they are not visible to the main program or other subprograms
Functions
Functions are subprograms which take several arguments as input and return a single output value or array. The following example illustrates the use and definition of a user-defined function to compute the distance between a point (x,y) and the origin (0,0).
-
real :: dist ! x,y are inputs and can’t be modified in the ! function: real, intent(in) :: x,y dist = sqrt(x*x + y*y) program functionExample implicit none real :: a,b, result a = 1.5 b = 2.0 ! Call function "dist". The result is placed in ! the variable "distance" result = dist(a,b) write (*,*) result !The subprograms are defined after "contains" contains function dist(x,y) ! All arguments to the function must be defined ! at the start of the function ! The variable with the same nametas the function ! is the returned value: end function dist end program functionExample
Program Output :
2.5000000
Subroutines
Fortran subroutines are similar to functions, except that they can return more than one variable or array to the calling program. Another difference is that the output values are returned via the arguments to the subroutine.
-
real, intent(out) :: r ! x,y are inputs and can’t be modified in the ! subroutine real, intent(in) :: x,y r = sqrt(x*x + y*y) program subExample implicit none real :: a,b,result a = 1.5 b = 2.0 ! Subroutine is called using the "call" keyword call dist(result,a,b) write (*,*) result ! The subprograms are defined after "contains" contains subroutine dist(r,x,y) ! Define all arguments at the top of the ! subroutine. r is the output: its value may be ! changed in the subroutine: end subroutine dist end program subExample
Program Output :
2.5000000