Download User-Defined Functions - Fortran Programming - Lecture Notes and more Study notes Computer Programming in PDF only on Docsity!
User-Defined Functions
- In addition to having the library functions available, the FORTRAN programmer may write her own functions.
- Each such function begins with a function header as follows:
ftype FUNCTION fname ( dummy-argument-list )
- The dummy arguments are used to receive values which are passed into the function from the "outside".
- The single result of the function, which is of ftype, is passed back ( returned ) to the "outside" through the function's name, fname
- Somewhere within the body of the function, a value must be assigned to the function name:
fname = expression
- If a user defined function does not have any arguments, an empty pair of parentheses () must appear in the FUNCTION header statement after the function name as follows:
ftype FUNCTION fname ()
- When the function is completed, it should execute a RETURN statement. Also, the physical end of the function should be marked by an END statement.
REAL FUNCTION DOAREA (R) C Computes the area of a circle with radius R. C Precondition : R is defined. C Postcondition: Function result is the circle area. C Argument declaration REAL R C Local declaration REAL PI PARAMETER (PI = 3.14159) C Define function result DOAREA = PI * R ** 2 C Exit function RETURN END C -------------------------------------------------------- REAL FUNCTION DOCIRC (R) C Computes the circumference of a circle with radius R. C Precondition : R is defined. C Postcondition: Function result is the circle circumference.
C Argument declaration REAL R C Local declaration REAL PI PARAMETER (PI = 3.14159) C Define function result DOCIRC = 2 * PI * R C Exit function RETURN END
Comments Within Functions
- The first few comment lines in a function should cover the following items: Ò Describe what the function does Ò Describe any preconditions which must be true before the function is called Ò Describe any post conditions which are true after the function has completed execution Ò Identify and describe each dummy argument
- These comments are useful to anyone wishing to use this function in another program.
- Additional comments should be included to identify the author, to describe each additional symbolic-name used in the function (local parameters, local variables, etc.) and to summarize each major step in the function's algorithm.
- This is done in a manner similar to a main program
Function Usage
- A user defined (programmed) function is referenced (called) in the same manner as a library function
- The program unit in which the function is referenced (used) must also contain a declaration statement to declare the type of the function that is being referenced.
Actual Arguments
- When a function is referenced; the constants, variables, and/or expressions which are used to pass values into the function are referred to as the actual arguments.
- These should not be confused with the dummy arguments which are the variables used within the function definition to receive the values being passed.
INTEGER FUNCTION ENTER (NMIN, NMAX) C Returns the first data value read between NMIN and NMAX. C Pre : NMIN is less than or equal to NMAX. C Post: Function result lies between NMIN and NMAX. C Argument Declarations INTEGER NMIN, NMAX C Declarations. INTEGER N LOGICAL BETWEN C Initially assume an integer between NMIN and NAMX is not entered. BETWEN = .FALSE. C Keep reading until an integer between NMIN and NMAX is entered. DO WHILE (.NOT. BETWEN) PRINT *, 'Enter an integer between ',
- NMIN, ' and ', NMAX READ *, N BETWEN = (N .GE. NMIN) .AND. (N .LE. NMAX) END DO C Define result. ENTER = N C Exit subroutine. RETURN END INTEGER FUNCTION FACTRL (N) C Computes the factorial of N. C Pre : N is greater than or equal zero. C Post: Function result is N!. C Argument Declarations. INTEGER N C Local Declarations. INTEGER I, PRODUC C Accumulate partial products in PRODUC. PRODUC = 1 DO 10 I = N, 2, - PRODUC = PRODUC * I 10 CONTINUE
C Define function result. FACTRL = PRODUC C Exit function. RETURN END
Validating Function Arguments (Defensive Programming)
- It is good programming style for a function to check the validity of its arguments.
- A function should respond to an invalid argument by printing an error message and attempting to return a usable result.
Usage Note
- A user defined function may reference library functions and other user defined functions;
- However, in FORTRAN 77, a function may not reference itself (be recursive) either directly or indirectly.
PROGRAM CIRCLE C Finds and prints the area and circumference of a circle. C The program user enters the circle radius and units of C measurement. C Declarations REAL RADIUS, AREA, CIRCUM CHARACTER *12 UNITS REAL DOAREA, DOCIRC C Read the value of RADIUS and UNITS PRINT *, 'Enter units (enclosed in apostrophes)' READ *, UNITS PRINT *, 'Enter radius (in ', UNITS, ')' READ *, RADIUS C Find the area AREA = DOAREA(RADIUS) C Find the circumference CIRCUM = DOCIRC(RADIUS) C Print the values of AREA and CIRCUM PRINT *, 'The area is ', AREA, ' square ', UNITS PRINT *, 'The circumference is ', CIRCUM, ' ', UNITS STOP END C ---------------------------------------------------------- C Insert function DOAREA here C ----------------------------------------------------------
Argument Correspondence
Modularity
- User written functions are independent program modules, or subprograms.
- A subprogram may not be executed by itself; it must be referenced (called) by a main program or another subprogram.
Function Positioning
- User written functions should be placed after the END statement of the main program in the source code file.
Name Independence
- Dummy arguments, local variable names, and local parameter names used within a function are unrelated to any other uses of these names in any other program unit, function or main program.
Argument List Correspondence
- The number of actual arguments in a function reference must be the same as the number of dummy arguments in the function definition.
- Also, the type of each actual argument used in a function reference must be the same as the type of the corresponding dummy argument.
- Again, be very careful with constants, 5 is not REAL and 5.0 is not INTEGER.
Side Effects
- It is poor programming practice for a function to change the value of any of its dummy arguments.
- Any such undesirable change is called a side effect.
Combinations : The number of ways to in which r items can be selected from a collection of n items without regard to order:
C( n , r ) =
n! r !( n − r )!
PROGRAM COMBIN C Computes the number of combinations of N items taken R at a C time. C Declarations. INTEGER N, R, C INTEGER FACTRL PRINT *, 'Enter number of items in the collection:' READ *, N PRINT *, 'Enter number of items to be selected:' READ *, R IF (R .LE. N) THEN C = FACTRL(N) / (FACTRL(R) * FACTRL(N-R)) PRINT *, 'The number of combinations is ', C ELSE PRINT *, 'Items to be selected cannot exceed total ',
- 'items' END IF C Exit program. STOP END C --------------------------------------------------------------- INTEGER FUNCTION FACTRL (N) C Computes the factorial of N. C Pre : N is greater than or equal to zero. C Post: Function result is N!. Actual code for factorial as before C Exit function. RETURN END
Single-Statement Functions:
Single Statement Functions
- If a function can be written as a single assignment statement, then the function may be defined within the referencing program unit as follows:
declaration-of-parameters definition-of-parameters : ftype fname (function name declaration) dummy-argument-declarations : fname ( dummy-argument-list ) = expression
- Examples REAL Z REAL HALF HALF(X) = X/ and REAL X, Y, C REAL HYPOT, SQUARE SQUARE(X) = X * X HYPOT(X, Y) = SGRT(SQUARE(X) + SQUARE(Y))
- If a function is declared in this manner, then the statement which assigns a value to the function name must come before any other executable statement within the program unit.
- In this situation, the dummy arguments may also be used as regular variables within the program unit.
LOGICAL Functions
- A function may be of type LOGICAL and return a logical value.
- Example: REAL NUM LOGICAL POSTIV POSTIV(NUM) = (NUM .GT. 0.0) ...
IF (POSTIV(X)) THEN
GOTO Statement
- The GOTO statement is used in FORTRAN to cause an immediate transfer of control from the GOTO statement to another statement within the FORTRAN program.
- The label in the GOTO statement must match a label on some other executable FORTRAN statement within the program.
Programming Style
- The use of the GOTO statement is generally considered to be harmful.
- Code written with numerous GOTO statements is referred to a spaghetti code.
Defining a Subroutine
Subroutine Definition
- A subroutine is a separate program module whose execution may return any number of results (including zero) to the calling program.
- A subroutine is defined in much the same manner as a function is declared
- A subroutine does not return a value through its name as a function does, so there is no need to give the subroutine's name a type nor to assign it a value within the body of the subroutine.
SUBROUTINE TABHED (STRNTH) C Displays the heading for the rebar table. C Argument Declarations. REAL STRNTH PRINT *, ' Joe Bob''s Steel Company' PRINT *, ' Rebar load chart' PRINT *, 'For bars with a steel strength of ', STRNTH,
- ' psi' PRINT * PRINT *, 'Bar Cross-sectional Max. Load' PRINT *, 'Number Area (sq. in.) (lbs.)' PRINT *, '------ --------------- ---------' C Exit subroutine. RETURN END
Dummy Arguments
- The dummy arguments are used to both pass values into the body of the subroutine and to pass results back to program unit using the subroutine.
- Dummy arguments are optional. A subroutine may be written without any arguments
Input Argument
- A dummy argument which is used only to pass a value into a subroutine (or function) and is not changed by the subroutine (or function) is called in input argument.
Output Argument:
- A dummy argument which is used only to pass a value out of a subroutine is called an output argument.
- It is assigned a value in the subroutine and may be used (accessed or reassigned) in the subroutine after the initial assignment.
- Output Arguments should not be used with functions.
Input/Output Argument
- A dummy argument which is used both to pass a value into a subroutine and to pass a result out of the subroutine is called an input/output argument.
- Input/output arguments should not be used with functions.
SUBROUTINE ORDER (S, L) C Arranges its arguments in numerical order. C Input/Output Arguments. C S - Smaller number after execution of ORDER. C L - Larger number after execution of ORDER. C Argument Declarations. REAL S, L C Local Declarations. REAL TEMP C Compare S and L and switch if necessary. IF (S .GT. L) THEN TEMP = S S = L L = TEMP END IF C Exit subroutine. RETURN END
Documentation
- A subroutine should be documented (commented) in much the same manner as a function or a main program
- The purpose of the subroutine, its preconditions and post conditions, and the description of each of its dummy arguments should be provided at the beginning in an "interface" section.
- Additional comments should be included to identify the author, to describe each additional symbolic-name used in the subroutine (local parameters, local variables, etc.) and to summarize each major step in the subroutine's algorithm.