Next: Procedures and Arrays
Up: Program Units
Previous: Recursive Procedures
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!,
- 4! is , so calculate 3! then multiply by 4,
- 3! is , need to calculate 2!,
- 2! is , 1! is and 0! = 1
- can now work back up the calculation and fill in the missing
values.
For more information, click here
Now try this question
Next: Procedures and Arrays
Up: Program Units
Previous: Recursive Procedures
©University of Liverpool, 1997
Wed May 28 23:37:18 BST 1997Not for commercial use.