! ===================================================   
! Demo function calling another function
! ===================================================
   PROGRAM Demo
   IMPLICIT NONE

   interface
     function f(x)
     integer f;
     integer, intent(in) :: x;
     end function
   end interface

   interface
     function SerieSum(f,x,y)
       integer SerieSum  
       interface
         function f(z)
         integer f;
	 integer, intent(in) :: z;
         end function f
       end interface

       integer, intent(in) :: x;
       integer, intent(in) :: y;
     end function
   end interface


   INTEGER :: x, y, sum

   print*, "Program somputes f(a) + f(a+1) + ... + f(b)"
   print*, "Start number a = "
   read*, x
   print*, "End number b = "
   read*, y

   sum = SerieSum(f, x,y)	      ! *** Pass f to SerieSum 

   print*, "Serie sum = ", sum
   print*
   STOP
   END



! ===================================================   
! Function returns f(a) + f(a+1) + ... + f(b)
! ===================================================
   FUNCTION SerieSum(f, a, b)
   IMPLICIT NONE										 
   INTEGER  SerieSum
   INTEGER, INTENT(IN) :: a
   INTEGER, INTENT(IN) :: b

   interface
     function f(x)
     integer f;
     integer, intent(in) :: x;
     end function f
   end interface
 
   INTEGER :: i

   SerieSum = 0

   DO i = a, b
     SerieSum = SerieSum + f(i)
   END DO

   RETURN
   END

! ===================================================   
! Function f(x) returns x*x
! ===================================================
   INTEGER FUNCTION f(x)
   IMPLICIT NONE										 
   INTEGER, INTENT(IN) :: x

   f = x*x
   RETURN
   END
