In this exercise we declare simple arrays, perform an operation on them, and then declare that operation as a function in a separate file.

The basic function performs a dot product on vectors with two integer components:

program dotProduct
implicit none             !requiring explicit declarations
integer                   :: c
integer, dimension(2)     :: a, b

write(*,*) 'Enter a''s components separated by a space'
read(*,*) a    !This will read a(1) and a(2)

write(*,*) 'Enter b''s components separated by a space'
read(*,*) b

c = a(1)*b(1) + a(2)*b(2)
write (*,*) c
end program dotProduct
Fortran

Write that to dotProduct.f90 and compile and run it.

$ gfortran dotProduct.f90 -o dotProduct
$ ./dotProduct
Shell session
$ ifort dotProduct.f90 -o dotProduct
$ ./dotProduct
Shell session

You are prompted to enter two vectors by component, and then given the dot product of the two vectors. Check that the answer is right!

Now we will do the same thing, but with dotProduct inside a function in a separate file. Call our first file calcDotProduct.f90:

program calcDotProduct
implicit none
integer                 :: dotProduct !Declare function as integer
integer, dimension(2)   :: a, b

write(*,*) 'Enter a''s components separated by a space'
read(*,*) a    !This will read a(1) and a(2)

write(*,*) 'Enter b''s components separated by a space'
read(*,*) b

write (*,*) dotProduct(a,b)

end program calcDotProduct
Fortran

Call this next file, the one where we are moving the function, dotProductFunc.f90:

integer function dotProduct(a,b)
implicit none
integer                   :: c
integer, dimension(2)     :: a, b

c = a(1)*b(1) + a(2)*b(2)

dotProduct = c            !The return value is assigned

return
end function dotProduct
Fortran

Now compile them together, then run it.

$ gfortran dotProductFunc.f90 calcDotProduct.f90 -o calcDotProduct
$ ./calcDotProduct
Shell session
$ ifort dotProductFunc.f90 calcDotProduct.f90 -o calcDotProduct
$ ./calcDotProduct
Shell session

It should behave the same as before.

 
© 2025  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Access Statement
CVW material development is supported by NSF OAC awards 1854828, 2321040, 2323116 (UT Austin) and 2005506 (Indiana University)