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,