Fortran 2003

Fortran 2003 is a standard of Fortran. This book will focus on modern Fortran, and it will not cover the obsolescent features of Fortran 77 and earlier standards.

Hello World
Here is a Hello World program in Fortran.

The "implicit none" statement forces the programmer to declare all variables, which is considered good style. Fortran has integer, character, real, complex, and logical data types. The following program illustrates their use.

output: i = 3  x = 3. z = (3.,3.) tf =  T

arithmetic operators
Fortran has the arithmetic operators +, -, /,*, and ** (for exponentiation). The output of

is

5 -1 0 12 8

Arrays
Fortran 90 and later versions have powerful functionality for arrays. The following program demonstrates some features of arrays. By default, array elements are numbered from 1, not 0, as in C or C++.

output:

vec = 9 4 1 vec(1) = 9, vec(3) = 1 size(vec), sum(vec), product(vec) = 3 14 36 minval(vec), maxval(vec) = 1 9 vec = 11 6 3 vec = 121 36 9

loops
Fortran uses do loops for iteration. For example, the program

gives output

1 1 2 4 3 9 i= 4 1 3 i= 5

because within the first loop, variable i takes on values between 1 and 3 with step size of 1, and in the second loop the step size is 2. After completing the loop the value of i is its last value before leaving the loop plus the step size.

comparison operators
Fortran has the comparison operators < <= /= == >= >, where /= means "not equal" and the other operators have the usual meanings. The program

has output

F F F T T T

do
One can have a DO loop without a counter variable, in which case an EXIT statement will be needed to leave the loop, as shown in the following program

Declaring max_fib a parameter means that its value cannot be changed in the rest of the program.

nested loops
Loops can be nested, as shown in the following program

which gives output

i,j= 1 1 i,j= 1 2 i,j= 2 1 i,j= 2 2 i,j= 3 1 i,j= 3 2

functions and return values
A function can be used to return a value depending on zero or more arguments. The code below shows a function that converts from degrees Fahrenheit to degrees Celsius.

Output:

degrees_F degrees_C 12.0    -11.1      32.0       0.0      52.0      11.1      72.0      22.2      92.0      33.3

subroutines
A subroutine cannot be used in an expression and is invoked with a call statement, as demonstrated in the program below, which gives the same output as the program above.

=See Also=
 * Fortran
 * Programming Language