Lecture 4
Lecture 4
MATTEO PASQUALI
[email protected]
713-348-5830
AL B-243
FORTRAN LECTURE 4
SUBPROGRAMS
PROBLEMS
1. PERFORM “SIMPLE” TASK MANY TIMES
AND RETURN A SINGLE VALUE,
POSSIBLY IN DIFFERENT PROGRAMS
FUNCTION
y = ax + bx + c
2 FUNCTION
INPUT: a, b, c, x
OUTPUT: y ONE
BLACK BOX SEPARATED OUTPUT
FROM MAIN PROGRAM
FUNCTION STATEMENT
SYNTAX
function FUNCTION_NAME (ARGUMENT_LIST )
function statement is followed by
implicit none
declaration of all variables in argument list
declaration of type of FUNCTION_NAME
declaration of local variables used in function
statements used to calculate FUNCTION_NAME
end function FUNCTION_NAME
INPUT: a, b, c, x
OUTPUT: y (value of quad. expr.) VALUE OF FUNCTION
IS STORED AND
function quadratic (x, a, b, c) RETURNED IN
FUNCTION NAME
implicit none
integer, parameter :: prec = selected_real_kind(13)
real (kind=prec), intent(in) :: x, a, b, c
real (kind=prec) :: quadratic
quadratic = a * x**2 + b * x + c
end function quadratic
EXAMPLE: VALUE OF A QUADRATIC EXPRESSION
program test
implicit none DECLARE
integer, parameter :: prec = selected_real_kind(13) FUNCTION
real (kind=prec) :: var, c1, c2, c3, yval NAME
real (kind=prec) :: quadratic
write(*,*) ‘coefficients of quadratic?’ NAME OF VARIABLES
read(*,*) c1, c2, c3 IN MAIN PROGRAM
write(*,*) ‘independent variable?’ AND FUNCTION
read(*,*) var
NEED NOT COINCIDE
yval = quadratic (var, c1, c2, c3)
write(*,*) ‘result’, yval TYPE OF VARIABLES
end program test IN MAIN PROGRAM
function quadratic (x, a, b, c)
AND FUNCTION
implicit none MUSTCOINCIDE
integer, parameter :: prec = selected_real_kind(13)
real (kind=prec), intent(in) :: x, a, b, c
real (kind=prec) :: quadratic
quadratic = a * x**2 + b * x + c
end function quadratic
SUBROUTINE STATEMENT
SYNTAX
subroutine SUB_NAME (ARGUMENT_LIST )
subroutine statement is followed by
implicit none
declaration of all variables in argument list
declaration of local variables used in subroutine
statements used to perform tasks
return
end subroutine SUB_NAME
ANY VALID FORTRAN STATEMENT CAN BE
USED IN THE BODY OF A SUBROUTINE
EXAMPLES OF SUBROUTINE TASKS
MANY
BLACK BOX SEPARATED OUTPUTS
FROM MAIN PROGRAM
FUNCTIONS VS. SUBROUTINES
IN IN
FUNCTION SUBROUTINE
OUT OUT
SUBROUTINE
integer :: i, k
PROGRAM
“LABELS”
“LABELS”
logical :: test
...
call task (a, test, b, i, k)
...
subroutine task (x, check, y, m, n)
... MEMORY
integer :: m, n a x
real :: x, y b y
logical :: check i m
...
k n
return
end subroutine task test check
INPUT vs. OUTPUT VARIABLES
INTENT ATTRIBUTE
VARIABLES IN ARGUMENT LIST CAN BE:
• INPUT ONLY, CANNOT BE CHANGED IN SUBROUTINE
intent (in)
• INPUT-OUTPUT, MUST BE PREDEFINED AND
CAN BE CHANGED IN SUBROUTINE
intent (inout)
• OUTPUT ONLY, NO DATA SHOULD BE PASSED TO
SUBROUTINE THROUGH IT
intent (out)
...
real, save :: partial_sum
...