Compaq Fortran 77 Release Notes for OpenVMS VAX Systems
*HyperReader
|
Example 2-1: Example of recursive function
PROGRAM FACTORIAL_TEST
!
! This is just a simple example program showing recursion in
! FORTRAN.
!
! The program computes and displays the factorials of the
! integers 1:12; factorial of 13 is too big for a longword
! integer.
!
INTEGER FACTORIAL
DO N=1,12
WRITE (6,*) N,' factorial is ',FACTORIAL(N)
END DO
END
OPTIONS /RECURSIVE
INTEGER FUNCTION FACTORIAL (N)
!
! The Factorial of an integer N is N * N-1 * N-2 ... * 1.
! This is often written as N!.
!
! If N is greater than 1, call ourselves recursively,
! passing N-1 to perform the calculation. Note that
! each recursive call to FACTORIAL will get its own
! copy of N.
!
! If N is 1 or less, the result is 1. (We assume that
! N is not negative.)
!
IF (N .GT. 1) THEN
FACTORIAL = FACTORIAL(N-1) * N
ELSE
FACTORIAL = 1
END IF
RETURN
END