next up previous contents
Next: Recursive Subroutine Example Up: Recursive Procedures Previous: Recursive Procedures

 

Recursive Function Example

The following program calculates the factorial of a number, n!, and uses n! = n(n-1)!

    PROGRAM Mayne
     IMPLICIT NONE
      PRINT*, fact(12) ! etc
    CONTAINS
     RECURSIVE FUNCTION fact(N) RESULT(N_Fact)
      INTEGER, INTENT(IN)  :: N
      INTEGER :: N_Fact ! also defines type of fact
       IF (N > 0) THEN
         N_Fact = N * fact(N-1)
       ELSE
         N_Fact = 1
       END IF
     END function FACT
    END PROGRAM Mayne

The INTEGER keyword in the function header specifies the type for both fact and N_fact.

The recursive function repeatedly calls itself, on each call the values of the argument is reduced by one and the function called again. Recursion continues until the argument is zero, when this happens the recursion begins to unwind and the result is calculated.

4! is evaluated as follows,

  1. 4! is tex2html_wrap_inline28562 , so calculate 3! then multiply by 4,
  2. 3! is tex2html_wrap_inline28570 , need to calculate 2!,
  3. 2! is tex2html_wrap_inline28576 , 1! is tex2html_wrap_inline28580 and 0! = 1
  4. can now work back up the calculation and fill in the missing values.

next up previous contents
Next: Recursive Subroutine Example Up: Recursive Procedures Previous: Recursive Procedures

©University of Liverpool, 1997
Wed May 28 20:20:27 BST 1997
Not for commercial use.