Functions in Fortran
Functions are central in Fortran. We’ll learn about functions with a few different examples.
To compile and run the Fortran program:
Here’s a breakdown of the Fortran code:
In Fortran, we define the main program using the
program
keyword.The
implicit none
statement is used to require explicit declaration of all variables.Functions in Fortran are defined using the
function
keyword, followed by the function name and its parameters.The
intent(in)
attribute specifies that the parameters are input-only and won’t be modified within the function.In Fortran, the function name itself acts as the return variable. We assign the result to the function name before the end of the function.
The
contains
keyword is used to include internal procedures (functions and subroutines) within the main program.To call a function, we use the syntax
function_name(args)
, similar to many other programming languages.
There are several other features to Fortran functions. One is the ability to return multiple values using subroutines, which we’ll look at next.