Here are a few examples of functions:
If the value supplied to a, b and c are 3, 5, and -2, respectively, Sum will receive 6 (=3+5+(-2)) and the function returns 6.INTEGER FUNCTION Sum(a, b, c) IMPLICIT NONE INTEGER, INTENT(IN) :: a, b, c Sum = a + b + c END FUNCTION Sum
The above function can be made much shorter by using LOGICAL assignment. In the following, if a > 0.0 is true, .TRUE. is stored to Positive; otherwise, Positive receives .FALSE.LOGICAL FUNCTION Positive(a) IMPLICIT NONE REAL, INTENT(IN) :: a IF (a > 0.0) THEN Positive = .TRUE. ELSE Positive = .FALSE. END IF END FUNCTION Positive
LOGICAL FUNCTION Positive(a) IMPLICIT NONE REAL, INTENT(IN) :: a Positive = a > 0.0 END FUNCTION Positive
The above example shows that you can declare other variables such as d, r1 and r2 if they are needed.REAL FUNCTION LargerRoot(a, b, c) IMPLICIT NONE REAL, INTENT(IN) :: a REAL, INTENT(IN) :: b REAL, INTENT(IN) :: c REAL :: d, r1, r2 d = SQRT(b*b - 4.0*a*c) r1 = (-b + d) / (2.0*a) r2 = (-b - d) / (2.0*a) IF (r1 >= r2) THEN LargerRoot = r1 ELSE LargerRoot = r2 END IF END FUNCTION LargerRoot
Note that the function name Factorial is not used in any computation. Instead, a new INTEGER variable is used for computing n!. The final value of Ans is stored to Factorial before leaving the function.INTEGER FUNCTION Factorial(n) IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER :: i, Ans Ans = 1 DO i = 1, n Ans = Ans * i END DO Factorial = Ans END FUNCTION
If Factorial is involved in computation like the following:
then there is a mistake although the above program looks normal. The reason is that the function name cannot appear in the right-hand side in any expression of that function.INTEGER FUNCTION Factorial(n) IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER :: i Factorial = 1 DO i = 1, n Factorial = Factorial * i END DO END FUNCTION
REAL FUNCTION GetNumber() IMPLICIT NONE DO WRITE(*,*) 'A positive real number --> ' READ(*,*) GetNumber IF (GetNumber > 0.0) EXIT WRITE(*,*) 'ERROR. Please try again.' END DO WRITE(*,*) END FUNCTION GetNumber