Why learn the oldest language still in use?
Tomorrow's weather forecast was almost certainly computed with Fortran. The global models run by the European Centre for Medium-Range Weather Forecasts, by national weather services and by climate research centres are large Fortran programs, as are many of the codes that simulate airflow over wings, the chemistry of new materials, the inside of stars and the behaviour of nuclear reactors. When a Python programmer calls a linear-algebra routine through NumPy or SciPy, the algorithms underneath were designed in, and are often still compiled from, Fortran libraries such as LAPACK.
There are good reasons for this, and only some of them are history. Fortran was designed for one job, turning mathematical formulas into fast machine code, and it is still very good at it. Arrays are part of the language, not a library. The rules about how variables may be aliased let compilers optimise aggressively. Decades of numerical libraries exist and are trusted. And on the largest supercomputers, Fortran, C and C++ are the languages with the most mature parallel toolchains.
The Fortran you will learn here is not the all-capitals, punched-card FORTRAN of old jokes. Modern Fortran has free-form source, modules, dynamic arrays, whole-array arithmetic, derived types with inheritance and polymorphism, built-in parallelism and a standard way to call and be called from C. Learning it is useful if you are heading into physics, engineering, climate science or high-performance computing, and it is a fascinating look at how a language can evolve for seventy years without abandoning its users.
From the IBM 704 to Fortran 2023
In 1953, programming meant writing machine code or assembly by hand, and most experts believed that no automatic translator could ever produce code as efficient as a skilled programmer's. John Backus, a young programmer at IBM, proposed to prove them wrong. His small team spent three years building a compiler for the IBM 704 that translated algebraic formulas into machine code, and they put enormous effort into optimisation, because they knew that if the result were much slower than hand-written code, nobody would use it. The first FORTRAN compiler was delivered in 1957. It worked, its output was competitive with hand-written code, and within a few years most scientific programming on IBM machines was done in FORTRAN. Backus received the Turing Award in 1977, in part for this work.
Fortran then became the first programming language with an official standard, and it has been revised ever since:
| Standard | Notable additions |
|---|---|
| FORTRAN 66 | the first standardised programming language (ANSI, 1966) |
| FORTRAN 77 | structured if ... then ... else, the character type; the fixed-form dialect still found in old code |
| Fortran 90 | free-form source, modules, whole-array operations, dynamic memory, derived types, recursion; the name stops being all capitals |
| Fortran 95 | pure and elemental procedures |
| Fortran 2003 | object-oriented programming, standard interoperability with C, IEEE floating-point control |
| Fortran 2008 | coarrays for parallel programming, do concurrent, submodules |
| Fortran 2018 | more parallel features (teams, events, collective subroutines), further C interoperability |
| Fortran 2023 | conditional expressions, enumeration types, and many smaller improvements |
This course teaches the language of Fortran 2008 and 2018, which current compilers support well, and mentions Fortran 2023 where it matters. Our examples are checked with GFortran 11 using -std=f2018, which rejects non-standard extensions, so everything here should compile with any modern compiler; newer GFortran releases add more of the 2018 and 2023 features.
Around 2020 a group of users and compiler developers founded the Fortran-lang community, which maintains fortran-lang.org, a standard library project, the Fortran Package Manager (fpm) and a busy forum. Lesson 8 introduces these tools.
Installing a compiler and compiling
Fortran is compiled ahead of time to machine code. Several good compilers exist: GFortran (part of GCC, free), LLVM Flang (the newer free compiler built on LLVM), Intel's ifx (free to download), NVIDIA's nvfortran for GPUs, and LFortran, an interactive compiler under development. This course uses GFortran:
- Linux:
sudo apt install gfortran(Debian, Ubuntu) orsudo dnf install gcc-gfortran(Fedora). - macOS: install Homebrew, then
brew install gcc; the compiler is calledgfortran. - Windows: use GFortran from MSYS2, or install a Linux distribution under WSL and follow the Linux instructions. Intel's ifx also works with Visual Studio.
Check with gfortran --version. Save a program in a file ending in .f90 and compile it:
gfortran -std=f2018 -Wall -o hello hello.f90
./hello-std=f2018 makes GFortran reject anything that is not standard Fortran 2018, which keeps your code portable; -Wall turns on useful warnings; -o hello names the executable. The file extension matters: .f90 (also used for code written to later standards, despite the name) means free-form source, while .f or .for means the old fixed form, in which columns 1 to 6 had special meanings inherited from punched cards. Write all new code in free form.
During development, professionals add run-time checks that the standard does not require:
gfortran -std=f2018 -Wall -Wextra -g -fcheck=all -fbacktrace -o sim sim.f90 # debugging
gfortran -O2 -march=native -o sim sim.f90 # production-fcheck=all catches array indices out of bounds and similar errors at run time, and -fbacktrace prints where a crash happened. These checks slow the program down, so they are switched off in optimised production builds.
First programs
Hello, Fortran
program hello
implicit none
print *, 'Hello, Fortran!'
end program helloIt prints:
Hello, Fortran!A Fortran program starts with program name and ends with end program name. implicit none comes first in every program, module and procedure you write (the last section explains why). print *, ... prints its items using list-directed formatting, where the * lets the compiler choose the layout; GFortran starts each line with a space, a habit inherited from line printers. Fortran is case-insensitive: PRINT, Print and print are the same, and modern style uses lowercase. Comments start with !. A statement ends at the end of the line; to continue one onto the next line, end the line with &.
Declarations, constants and formats
! How long does a stone take to fall, ignoring air resistance?
program free_fall
implicit none
real, parameter :: g = 9.81 ! m/s², a named constant
real :: height, time, speed
integer :: floors
floors = 12
height = floors * 3.0 ! about 3 m per storey
time = sqrt(2.0 * height / g)
speed = g * time
print *, 'Height (m):', height
print *, 'Time (s): ', time
print '(a, f6.2, a)', 'Fall time: ', time, ' s'
print '(a, f6.1, a, f6.1, a)', 'Impact speed: ', speed, ' m/s, or ', speed * 3.6, ' km/h'
print '(a, i0, a)', 'That was ', floors, ' floors.'
end program free_fallIt prints:
Height (m): 36.0000000
Time (s): 2.70914173
Fall time: 2.71 s
Impact speed: 26.6 m/s, or 95.7 km/h
That was 12 floors.All declarations come at the top of the program, before the first executable statement. real and integer are two of Fortran's intrinsic types; real is a single-precision floating-point number by default (lesson 5 shows how to ask for double precision, which most scientific code uses). parameter makes a named constant, which the compiler substitutes everywhere and which cannot be changed. sqrt is one of Fortran's many intrinsic procedures, built-in functions that need no import.
The output shows the two kinds of printing. List-directed print * printed 36.0000000 and 2.70914173 with as many digits as a real holds, in a layout that differs from compiler to compiler. For output people will read, give an explicit format in parentheses as the first item of print:
| Edit descriptor | Meaning | Example |
|---|---|---|
a | a character string | 'Fall time: ' |
i0 | an integer in as few characters as needed | 12 |
i5 | an integer right-aligned in 5 characters | 12 |
f6.2 | a real in 6 characters with 2 decimals | 2.71 |
es12.4 | a real in scientific notation | 2.7091E+00 |
Note that floors * 3.0 multiplied an integer by a real; Fortran converted the integer to real before multiplying, a rule called mixed-mode arithmetic, which the next lesson treats with care.
A loop: Newton's method
Isaac Newton's method for square roots improves a guess for by replacing it with the average of and . Each step roughly doubles the number of correct digits:
! Newton's method for a square root, the way Fortran's first users computed it.
program newton_sqrt
implicit none
real :: x, guess, previous
integer :: step
x = 2.0
guess = x ! any positive starting guess works
do step = 1, 20
previous = guess
guess = 0.5 * (guess + x / guess)
print '(a, i2, a, f12.9)', 'step ', step, ': ', guess
if (abs(guess - previous) < 1.0e-6 * guess) exit
end do
print '(a, f12.9)', 'intrinsic sqrt: ', sqrt(x)
end program newton_sqrtIt prints:
step 1: 1.500000000
step 2: 1.416666746
step 3: 1.414215684
step 4: 1.414213538
step 5: 1.414213538
intrinsic sqrt: 1.414213538do step = 1, 20 ... end do is Fortran's counting loop: step takes the values 1, 2, ..., 20. exit leaves the loop early, here when two successive guesses agree to about six significant digits, which is roughly what a default real can hold. Notice that after step 4 nothing changes any more: 1.414213538 is the closest single-precision number to , and it matches the intrinsic sqrt exactly. The digits printed beyond the seventh are not meaningful; f12.9 simply asked for nine decimals.
Reading the Fortran you will meet at work
Most professional Fortran programmers spend part of their time in code that is older than they are. A climate model or a structural-analysis package may contain modern modules written last year next to routines written in the 1980s, and you need to be able to read both. Here is the same Newton iteration written in the fixed-form style of FORTRAN 77:
C NEWTON ITERATION FOR SQRT(X), FIXED-FORM FORTRAN 77 STYLE
PROGRAM ROOT
REAL X, G, GOLD
INTEGER I
X = 2.0
G = X
DO 10 I = 1, 20
GOLD = G
G = 0.5*(G + X/G)
IF (ABS(G - GOLD) .LT. 1.0E-6*G) GOTO 20
10 CONTINUE
20 WRITE (*,*) G
ENDThe layout comes from 80-column punched cards. A C (or *) in column 1 marks a comment; columns 1 to 5 hold optional statement labels such as 10 and 20; any character in column 6 marks a continuation line; statements go in columns 7 to 72, and anything beyond column 72 is ignored, which once made a famous class of bugs. Loops end at a labelled CONTINUE, early exits are GOTOs, and comparisons are written .LT., .GE. and so on (modern Fortran also allows <, >=). There is no IMPLICIT NONE, so I is an integer only because of its first letter. Saved as root.f, this still compiles with gfortran -std=f2018 and prints 1.41421354; GFortran 11 merely warns Fortran 2018 obsolescent feature: Labeled DO statement, its way of saying the construct is legal but should not be used in new code.
You will also meet COMMON blocks (shared global storage, replaced by module variables), EQUIVALENCE (two names for the same memory), and arguments whose array sizes are passed separately. Compilers still accept nearly all of it, so old and new code can be linked into one program, and modernising a large code is usually done gradually, one routine at a time, behind tests.
A modern Fortran program is built from a few kinds of program units: one main program, any number of modules (lesson 4) holding procedures, types and data, and submodules for separating a module's interface from its implementation. Each source file is compiled to an object file, gfortran -c physics.f90 produces physics.o and a physics.mod file describing the module's interface, and the objects are linked into an executable. Because a module must be compiled before any file that uses it, build tools have to work out the order; lesson 8 shows how fpm does this for you.
implicit none, and other surprises
Misconception
"Fortran makes you declare variables." It does not, unless you ask it to. For compatibility with the oldest code, Fortran still has implicit typing: any undeclared name starting with I, J, K, L, M or N is an integer, and any other undeclared name is a real. This program compiles and runs without complaint:
! Without implicit none, a typo silently creates a new variable.
program typo
real :: total
integer :: k
total = 0.0
do k = 1, 10
totl = total + k ! misspelled: Fortran invents a REAL called totl
end do
print *, 'sum of 1..10 =', total
end program typoIt prints:
sum of 1..10 = 0.00000000 The misspelled totl silently became a new real variable, so total never changed. Add implicit none after the program line and the compiler catches the mistake. GFortran 11 reports:
typo_fixed.f90:8:9:
8 | totl = total + k ! misspelled: Fortran invents a REAL called totl
| 1
Error: Symbol ‘totl’ at (1) has no IMPLICIT type; did you mean ‘total’?Every program, module and procedure in this course begins with implicit none. (Inside a module it only needs to be written once, at the top.) Fortran 2018 also offers implicit none (type, external), which additionally requires every external procedure to be declared.
Misconception
".f90 means the code is Fortran 90." The extension only tells the compiler that the source is in free form. Code written to the 2018 standard is still normally saved as .f90.
Misconception
"Old habits like real*8 are fine." real*8 and double precision appear everywhere in older code, but real*8 was never standard. With -std=f2018, GFortran 11 rejects it with Error: GNU Extension: Nonstandard type declaration REAL*8. Lesson 5 shows the portable way to choose precision.
Exercises
1. First steps in Fortran
CoreComputationalIn a program without implicit none, a programmer uses two undeclared variables, nsteps and velocity. What types does Fortran give them?
2. First steps in Fortran
Warm-upComputationalWhat does print '(a,i5,a)', '[', 42, ']' print?
3. First steps in Fortran
CoreComputationalWhat does print '(a,f6.2,a)', '[', 3.14159, ']' print?
4. First steps in Fortran
Warm-upComputationalWhat does print '(a, i0)', 'n=', 7*6 print?
5. First steps in Fortran
CoreComputationalWhat does this program print?
program e1
implicit none
integer :: X
x = 5
X = X + 1
print '(i0)', x
end program e1
6. First steps in Fortran
Warm-upHumanWhat does the GFortran option -std=f2018 do?
7. First steps in Fortran
Warm-upHumanIn what year was the first FORTRAN compiler delivered, for the IBM 704?
Further reading and resources
- The History of FORTRAN I, II and III · John Backus · 1978Backus's own account, written for the first ACM History of Programming Languages conference, of how the first compiler was built.
- Fortran-lang, Learn FortranThe community's tutorials and quick-start guide to modern Fortran.
- GNU Fortran, command optionsEvery GFortran option, including -std, the warning options and the run-time checks.
- ISO/IEC JTC1/SC22/WG5The Fortran standards committee, with summaries of what each standard added.