Structure of function subprograms

A function subprogram is a complete, separate program that computes a single value that is returned to the main program in the function name. A function subprogram may contain any Fortran statement. Here is an example of a function which calculates an average of three numbers a, b, c:

      real function AVERAGE(a,b,c) 
      implicit none

      real a, b, c

      AVERAGE = (a+b+c)/3.0

      end
This expression says that our function has the name AVERAGE and returns one value of type real which will, of course, be the average of the three numbers a,b,c given as arguments. The result is returned from our function by statement AVERAGE = ...

Each function is a separate subprogram which can be called from the main program part, or any other function or subroutine of your code. In order to make our function AVERAGE accessible from a particular place in your program, you have to first declare it, similarly as we are used to declare variables:

      real AVERAGE
Hence, the function AVERAGE can be used from the program/function/subroutine in which it was declared. Assuming that we have three numbers num1, num2, num3, you can calculate their average by simply calling
      :
      navg = AVERAGE(num1,num2,num3)
      :
Obviously, the data type of navg has to be first declared to be real, same as the return type of the function AVERAGE.

Problem: Write a function which calculates the factorial of a given number. Write a program part which calls this function and prints the result.

Solution:

      program MAIN

      integer num, res, FACT
      parameter( num=5 )

      res = FACT(num)
      write(*,'("Factorial of ",I3," is ",I5)')
     +     num, res

      end

!-------------------------------------------------                                                  

      integer function FACT(n)
      implicit none

      integer i, res, n

      res = 1
      do i=2,n
         res = res*i
      enddo

      FACT = res

      end

Now, it should be clear to you that the statement res = FACT(num) in the MAIN part of the code above calls the function FACT which calculates the factorial of num and returns the result in res. Note also, that the function FACT was declared by integer FACT before actually using it.

Roman Gröger (2015-09-23)