Fortran/Fortran examples

The following Fortran code examples or sample programs show different situations depending on the compiler. The first set of examples are for the Fortran II, IV, and 77 compilers. The remaining examples can be compiled and run with any newer standard Fortran compiler (see the end of the main Fortran article for lists of compilers). By convention most contemporary Fortran compilers select the language standard to use during compilation based on source code file name suffix: FORTRAN 77 for  (or the less common  ), Fortran 90 for , Fortran 95 for. Other standards, if supported, may be selected manually with a command line option.

FORTRAN II, IV, and 77 compilers
NOTE: Before FORTRAN 90, most FORTRAN compilers enforced fixed-format source code, a carryover from IBM punch cards
 * comments must begin with a * or C or ! in column 1
 * statement labels must occur in columns 1-5
 * continuation lines must have a non-blank character in column 6
 * statements must start in column 7
 * the line-length may be limited to 72 characters (derived from the 80-byte width of a punch-card, with last 8 characters reserved for (optional) sequence numbers)

If errors are produced when you compile your FORTRAN code, first check the column alignment. Some compilers also offer free form source by using a compiler flag

Simple Fortran II program
One data card input

If one of the input values is zero, then the program will end with an error code of "1" in the job control card listing following the execution of the program. Normal output will be one line printed with A, B, C, and AREA. No specific units are stated.

Simple Fortran IV program
Multiple data card input

This program has two input checks: one for a blank card to indicate end-of-data, and the other for a zero value within the input data. Either condition causes a message to be printed.

Simple Fortran 77 program
Multiple data card input

This program has two input checks in the READ statement with the END and ERR parameters, one for a blank card to indicate end-of-data; and the other for zero value along with valid data. In either condition, a message will be printed.

"Retro" FORTRAN IV
A retro example of a FORTRAN IV (later evolved into FORTRAN 66) program deck is available on the IBM 1130 page, including the IBM 1130 DM2 JCL required for compilation and execution. An IBM 1130 emulator is available at IBM 1130.org that will allow the FORTRAN IV program to be compiled and run on a PC.

Hello, World program
In keeping with computing tradition, the first example presented is a simple program to display the words "Hello, world" on the screen (or printer).

FORTRAN 66 (also FORTRAN IV)
This program prints "HELLO, WORLD" to Fortran unit number 6, which on most machines was the line printer or terminal. (The card reader or keyboard was usually connected as unit 5). The number 7 in the  statement refers to the statement number of the corresponding   statement. statements may be placed anywhere in the same program or function/subroutine block as the  statements which reference them. Typically a  statement is placed immediately following the   statement which invokes it; alternatively,   statements are grouped together at the end of the program or subprogram block. If execution flows into a  statement, it is a no-op; thus, the example above has only two executable statements,   and.

The initial  in the   statement in the above example defines a Hollerith constant, here meaning that the 13 characters immediately following are to be taken as a character constant (note that the Hollerith constant is not surrounded by delimiters). (Some compilers also supported character literals enclosed in single quotes, a practice that came to be standard with FORTRAN 77.)

The space immediately following the 13H is a carriage control character, telling the I/O system to advance to a new line on the output. A zero in this position advances two lines (double space), a 1 advances to the top of a new page and + character will not advance to a new line, allowing overprinting.

FORTRAN 77
As of FORTRAN 77, single quotes are used to delimit character literals, and inline character strings may be used instead of references to  statements. Comment lines may be indicated with either a  or an asterisk  in column 1.

Fortran 90
As of Fortran 90, double quotes are allowed in addition to single quotes. An updated version of the Hello, world example (which here makes use of list-directed I/O, supported as of FORTRAN 77) could be written in Fortran 90 as follows:

Greatest common divisor
The following introductory example in FORTRAN 77 finds the greatest common divisor for two numbers $$A$$ and $$B$$ using a verbatim implementation of Euclid's algorithm.

The above example is intended to illustrate the following:
 * The  and   statements in the above use ' ' as a format, specifying list-directed formatting. List-directed formatting instructs the compiler to make an educated guess about the required input or output format based on the following arguments.
 * As the earliest machines running Fortran had restricted character sets, FORTRAN 77 uses abbreviations such as,  ,  ,  ,  , and   to represent the relational operators =, ≠, <, >, ≤, and ≥, respectively.
 * This example relies on the implicit typing mechanism to specify the INTEGER types of,  ,  ,  , and.
 * In the function, the values of the function arguments   and   are copied into the local variables   and   respectively. This is necessary as the values of   and   are altered within the function. Because argument passing in Fortran functions and subroutines utilize call by reference by default (rather than call by value, as is the default in languages such as C), modifying   and   from within the function would effectively have modified the corresponding actual arguments in the main   unit which called the function.

The following shows the results of compiling and running the program.

Complex numbers
The following FORTRAN 77 example prints out the values of $$e^{j i \pi / 4}$$ (where $$j = \sqrt{-1}$$) for values of $$i = 0, 1, \ldots, 7$$.

The above example is intended to illustrate the following:
 * The  statement can be used to specify the implicit type of variables based on their initial letter if different from the default implicit typing scheme described above. In this example, this statement specifies that the implicit type of variables beginning with the letter   shall be.
 * The  statement may be used to specify constants. The second constant in this example  is given the complex-valued value $$0 + j1$$, where $$j$$ is the imaginary unit $$\sqrt{-1}$$.
 * The first number in the  statement specifies the number of the last statement considered to be within the body of the   loop. In this example, as neither the   nor the   is a single executable statement, the   statement (which does nothing) is used simply in order for there to be some statement to denote as the final statement of the loop.
 * corresponds to the exponential function $$e^x$$. In FORTRAN 77, this is a generic function, meaning that it accepts arguments of multiple types (such as  and, in this example,  ). In FORTRAN 66, a specific function would have to be called by name depending on the type of the function arguments (for this example,   for a  -valued argument).
 * When applied to a -valued argument,   and   return the values of the argument's real and imaginary components, respectively.

Incidentally, the output of the above program is as follows (see the article on Euler's formula for the geometric interpretation of these values as eight points spaced evenly about a unit circle in the complex plane).

Error can be seen occurring in the last decimal place in some of the numbers above, a result of the  data type representing its real and imaginary components in single precision. Incidentally, Fortran 90 also made standard a double-precision complex-number data type (although several compilers provided such a type even earlier).

Summations with a DO loop
In this example of Fortran 90 code, the programmer has written the bulk of the code inside of a DO loop. Upon execution, instructions are printed to the screen and a SUM variable is initialized to zero outside the loop. Once the loop begins, it asks the user to input any number. This number is added to the variable SUM every time the loop repeats. If the user inputs 0, the EXIT statement terminates the loop, and the value of SUM is displayed on screen.

Also apparent in this program is a data file. Before the loop begins, the program creates (or opens, if it has already been run before) a text file called "SumData.DAT". During the loop, the WRITE statement stores any user-inputted number in this file, and upon termination of the loop, also saves the answer.

When executed, the console would display the following:

And the file SumData.DAT would contain:

Calculating cylinder area
The following program, which calculates the surface area of a cylinder, illustrates free-form source input and other features introduced by Fortran 90.

Dynamic memory allocation and arrays
The following program illustrates dynamic memory allocation and array-based operations, two features introduced with Fortran 90. Particularly noteworthy is the absence of  loops and  /  statements in manipulating the array; mathematical operations are applied to the array as a whole. Also apparent is the use of descriptive variable names and general code formatting that comport with contemporary programming style. This example computes an average over data entered interactively.

Writing functions
Modern Fortran features available for use with procedures, including deferred-shape, protected, and optional arguments, are illustrated in the following example, a function to solve a system of linear equations.

Note that an explicit interface to this routine must be available to its caller so that the type signature is known. This is preferably done by placing the function in a  and then  ing the module in the calling routine. An alternative is to use an  block, as shown by the following example:

Writing subroutines
In those cases where it is desired to return values via a procedure's arguments, a subroutine is preferred over a function; this is illustrated by the following subroutine to swap the contents of two arrays:

As in the previous example, an explicit interface to this routine must be available to its caller so that the type signature is known. As before, this is preferably done by placing the function in a  and then  ing the module in the calling routine. An alternative is to use a  block.

Internal and Elemental Procedures
An alternative way to write the  subroutine from the previous example, is:

In the example, the  subroutine is elemental, i.e., it acts upon its array arguments, on an element-by-element basis. Elemental procedures must be pure (i.e., they must have no side effects and can invoke only pure procedures), and all the arguments must be scalar. Since  is internal to the   subroutine, no other program unit can invoke it.

The following program serves as a test for any of the two  subroutines presented:

Pointers and targets methods
In Fortran, the concept of pointers differs from that in C-like languages. A Fortran 90 pointer does not merely store the memory address of a target variable; it also contains additional descriptive information such as the target's rank, the upper and lower bounds of each dimension, and even strides through memory. This allows a Fortran 90 pointer to point at submatrices.

Fortran 90 pointers are "associated" with well-defined "target" variables, via either the pointer assignment operator or an   statement. When appearing in expressions, pointers are always dereferenced; no "pointer arithmetic" is possible.

The following example illustrates the concept:

Module programming
A module is a program unit which contains data definitions, global data, and ed procedures. Unlike a simple  file, a module is an independent program unit that can be compiled separately and linked in its binary form. Once compiled, a module's public contents can be made visible to a calling routine via the  statement.

The module mechanism makes the explicit interface of procedures easily available to calling routines. In fact, modern Fortran encourages every  and   to be  ed in a. This allows the programmer to use the newer argument passing options and allows the compiler to perform full type checking on the interface.

The following example also illustrates derived types, overloading of operators and generic procedures.