User-Defined
Functions
References: Section 9 of the FORTRAN95 Manual and the Fortran Lecture4
A function is a self-contained, separate subprogram. We have intrinsic or build-in functions in FORTEAN such as SQRT, y=sqrt(x). We can write our own functions, which are called user-defined functions. The subprogram of a function can be written in the same file as the main program, or it can be saved in a separate file. When a main program uses a function which is not in the same file as the main program, we need to link the main program with the function file when building the executable file.
The general form of a function subprogram:
[type]
FUNCTION name (argument-list)
[IMPLICIT NONE]
type declarations
executable statements
END [FUNCTION [name]]
More
than one data from the main program can be passed on to the function, via the
argument-list. Only one number can be transferred back to the main program via
the function name. For example, consider a program which calculates distance
from the origin, ![]()
PROGRAM EXAMPLE
PRINT *, 'Input X, Y'
READ *, X, Y
r = RADIUS( X, Y )
PRINT *, 'Distance = ', r
END PROGRAM EXAMPLE
!=========================
REAL FUNCTION RADIUS( A,
B )
RADIUS = SQRT( A ** 2 +
B ** 2 )
PRINT *, A,B
END FUNCTION RADIUS
Exercises
1) In the example program, what is the function name? How many arguments in the function argument-list? How are the arguments separated?
2) IF the input in the main program for X and Y are 3 and 4, what is the output in the function for A and B? What is the output for the distance r in the main program?
3) If IMPLICIT NONE is used in the program, what changes have to be made?
4) Write a main program (distance.f95), which uses the same function in the example program to calculate the distance between two points (x1,y1) and (x2,y2). What is the distance between (5,6) and (15,16)?
5) Prog17 in the Fortran Lecture4 uses a user-defined function volume(r,h) to compute the volume of a cylinder. Add a new function area(r,h):
area(r,h) = 2*pi*r*h + 2*pi*r**2
And use this function to calculate the surface area and output the result in the main program. (save the program as prog17.f95)
For r = 2 and h = 0.5, what are the volume and the surface area?