next up previous contents
Next: Procedures and Arrays Up: Program Units Previous: Recursive Procedures

 

Recursive Function Example

The following example calculates the factorial of a number 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

To calculate 4!,

  1. 4! is tex2html_wrap_inline27833 , so calculate 3! then multiply by 4,
  2. 3! is tex2html_wrap_inline27841 , need to calculate 2!,
  3. 2! is tex2html_wrap_inline27847 , 1! is tex2html_wrap_inline27851 and 0! = 1
  4. can now work back up the calculation and fill in the missing values.

For more information, click here gif

Now try this question gif


next up previous contents
Next: Procedures and Arrays Up: Program Units Previous: Recursive Procedures

©University of Liverpool, 1997
Wed May 28 23:37:18 BST 1997
Not for commercial use.