A small, strict core
Fortran's core is small: five intrinsic types, a handful of control constructs and a set of intrinsic functions. It is also strict in ways that newer languages are not. Every variable has a fixed type declared at the top of its scope (with implicit none, as you saw in lesson 1). Integer and real arithmetic follow rules that are simple but unforgiving. Strings have a fixed length unless you ask otherwise. This strictness is part of why compilers can make Fortran fast, and once you know the rules there are few surprises left.
This lesson goes through the types and their arithmetic, then strings, then the control-flow constructs. Along the way it points out the half-dozen traps that catch everyone who comes to Fortran from Python, C or Julia.
The intrinsic types
Definition— Intrinsic types
Fortran has five intrinsic types: integer (whole numbers), real (floating-point numbers), complex (pairs of reals), logical (.true. or .false.) and character (text). Each comes in one or more kinds, such as single- and double-precision real; without a kind, you get the default kind, which for real is usually 32-bit single precision.
Declarations have the form type, attributes :: names. The most common attribute so far is parameter, which makes a named constant:
integer :: count, i
real :: mass, velocity
real, parameter :: pi = 3.14159265
logical :: converged = .false.
character(len=20) :: nameHere is how the types behave:
! Fortran's intrinsic types and the arithmetic rules that surprise newcomers
program types_tour
implicit none
integer :: i, j
real :: x
complex :: z
logical :: ok
i = 7
j = 2
print *, '7 / 2 =', i / j ! integer division truncates
print *, '-7 / 2 =', -i / j ! ... towards zero
print *, 'mod(-7, 2) =', mod(-i, j), ' modulo(-7, 2) =', modulo(-i, j)
print *, 'real(7) / 2 =', real(i) / j ! mixed mode: the integer is converted
print *, '2**10 =', 2**10, ' 2.0**0.5 =', 2.0**0.5
print *, 'nint(2.5), nint(-2.5), floor(-2.5), int(-2.5):', nint(2.5), nint(-2.5), floor(-2.5), int(-2.5)
print *, 'largest default integer:', huge(i)
print *, 'default real: epsilon =', epsilon(x), ' digits =', precision(x)
x = 0.1
print *, '0.1 stored as a default real:', x
print '(a, f12.10)', ' 0.1 + 0.2 to ten decimals: ', 0.1 + 0.2
z = (3.0, 4.0) ! 3 + 4i
print *, 'z =', z, ' |z| =', abs(z), ' z*conjg(z) =', z * conjg(z)
ok = (i > j) .and. .not. (i == 0)
print *, 'logical:', ok, .true. .neqv. .false.
end program types_tourIt prints:
7 / 2 = 3
-7 / 2 = -3
mod(-7, 2) = -1 modulo(-7, 2) = 1
real(7) / 2 = 3.50000000
2**10 = 1024 2.0**0.5 = 1.41421354
nint(2.5), nint(-2.5), floor(-2.5), int(-2.5): 3 -3 -3 -2
largest default integer: 2147483647
default real: epsilon = 1.19209290E-07 digits = 6
0.1 stored as a default real: 0.100000001
0.1 + 0.2 to ten decimals: 0.3000000119
z = (3.00000000,4.00000000) |z| = 5.00000000 z*conjg(z) = (25.0000000,0.00000000)
logical: T TThe rules to remember:
- Integer division truncates towards zero.
7 / 2is 3 and-7 / 2is −3. For remainders,modtakes the sign of the first argument andmodulothe sign of the second, which is what you want for wrapping around a periodic grid. - Mixed-mode arithmetic converts the integer. In
real(i) / j, the real numerator forcesjto be converted, giving 3.5. But inreal(i / j)the integer division happens first and you get 3.0, one of the commonest bugs in scientific Fortran. - Conversions are explicit and named.
real(i)converts to real;inttruncates towards zero;nintrounds to the nearest integer, with halves going away from zero (sonint(2.5)is 3, unlike Julia's or Python's rounding);floorandceilinground down and up. **is exponentiation. An integer exponent, as inx**2, is computed by multiplication and is exact; a real exponent, as in2.0**0.5, uses logarithms.- Default reals are single precision.
epsilon(x)is about 1.2 × 10⁻⁷ andprecision(x)reports 6 decimal digits, so0.1is stored as0.100000001. This is fine for some purposes and far too coarse for most scientific computing; lesson 5 shows how to use double precision properly. - The default integer is 32 bits on most compilers, so
huge(i)is 2 147 483 647. Overflowing it is not an error the compiler must report: the standard says nothing about what happens, and in practice the value usually wraps around. Use a 64-bit kind (lesson 5) for large counts. - Complex numbers are built in.
(3.0, 4.0)is 3 + 4i, andabs,conjgand the elementary functions all work on them. - Logicals print as
TandFin list-directed output. The operators are.and.,.or.,.not.,.eqv.and.neqv.; comparisons can be written==,/=,<,<=,>,>=, or in the old style.eq.,.ne.,.lt.and so on. Note that "not equal" is/=, not!=, which in Fortran would start a comment.
Character strings
Fortran's strings work differently from those of most languages. A variable declared character(len=12) always holds exactly 12 characters: shorter values are padded with blanks, longer ones are cut off.
! Character strings: fixed length, trimming, slicing, searching and growing
program strings
implicit none
character(len=12) :: city ! always exactly 12 characters
character(len=:), allocatable :: line ! length decided at run time
character(len=20) :: buffer
integer :: pos, k, code
city = 'Kraków'
print '(a)', '[' // city // ']' ! padded with blanks to 12
print '(a)', '[' // trim(city) // ']'
print *, 'len =', len(city), ' len_trim =', len_trim(city)
line = 'Lagos' ! allocated to length 5
line = line // ', Nigeria' ! reallocated automatically
print '(a, a, i0, a)', line, ' (', len(line), ' characters)'
print '(a)', line(1:3) ! a substring
pos = index(line, ',')
print '(a, i0)', 'comma at position ', pos
print '(a)', 'country: ' // trim(adjustl(line(pos+1:)))
! Numbers to text with an internal write (a write into a string)
write (buffer, '(i0, a, f0.2)') 42, ' items at ', 3.5
print '(a)', trim(buffer)
! There is no built-in upper-case function, so loop over the characters
do k = 1, len(line)
code = iachar(line(k:k))
if (code >= iachar('a') .and. code <= iachar('z')) line(k:k) = achar(code - 32)
end do
print '(a)', line
end program stringsIt prints:
[Kraków ]
[Kraków]
len = 12 len_trim = 7
Lagos, Nigeria (14 characters)
Lag
comma at position 6
country: Nigeria
42 items at 3.50
LAGOS, NIGERIA- Padding and trimming.
cityprinted with five trailing blanks;trimremoves them, andlen_trimcounts the characters before the blanks. - Characters are bytes.
len_trimreported 7 forKraków, which has six letters, because default Fortran characters are bytes andótakes two bytes in UTF-8. Text in English works as you expect; for serious multilingual text processing, Fortran is not the right tool, though some compilers support a widercharacter(kind=...). - Deferred-length strings.
character(len=:), allocatable(Fortran 2003) declares a string whose length is set by assignment and changes automatically when you assign a longer value. Use it whenever the length is not known in advance. When this program was compiled, GFortran 11 with-Wallprinted two warnings thatline"may be used uninitialized"; they are false alarms from the optimiser's analysis of the hidden length variable, and the program is correct. - Concatenation and substrings.
//joins strings, andline(1:3)is the substring of characters 1 to 3;line(pos+1:)runs to the end. - Searching and tidying.
indexfinds a substring (0 if absent), andadjustlmoves leading blanks to the end, sotrim(adjustl(s))removes blanks from both sides. - Internal I/O. Writing to a character variable instead of a file converts numbers to text using a format;
i0andf0.2mean "as narrow as possible". Reading from a string, as inread (text, *) x, converts the other way. - Character codes.
iachargives a character's ASCII code andacharthe character for a code, which is enough to write the upper-casing loop that Fortran's standard library lacks.
Control flow
! Control flow: if, select case, counted and conditional loops, named loops
program control
implicit none
integer :: mark, k, a, b, years
integer, parameter :: marks(6) = [95, 82, 67, 49, 100, 73]
real :: balance
character(len=1) :: grade
! select case chooses by value, including ranges
do k = 1, size(marks)
mark = marks(k)
select case (mark)
case (90:)
grade = 'A'
case (75:89)
grade = 'B'
case (50:74)
grade = 'C'
case default
grade = 'F'
end select
write (*, '(i4, 1x, a)', advance='no') mark, grade
end do
print *
! A counted loop can run backwards with a step
do k = 10, 1, -3
write (*, '(i3)', advance='no') k
end do
print *
! do while: how many years until savings double at 6% interest?
balance = 1000.0
years = 0
do while (balance < 2000.0)
balance = balance * 1.06
years = years + 1
end do
print '(a, i0, a, f8.2)', 'doubled after ', years, ' years: ', balance
! Named loops: 1729 = a**3 + b**3 in two different ways (Hardy and Ramanujan's taxi)
search: do a = 1, 12
do b = a, 12
if (a**3 + b**3 > 1729) cycle search ! larger b only makes it bigger
if (a**3 + b**3 == 1729) then
print '(a, i0, a, i0, a)', '1729 = ', a, '**3 + ', b, '**3'
end if
end do
end do search
end program controlIt prints:
95 A 82 B 67 C 49 F 100 A 73 C
10 7 4 1
doubled after 12 years: 2012.20
1729 = 1**3 + 12**3
1729 = 9**3 + 10**3The constructs, one by one:
select casepicks a branch by value. Cases can be single values, lists such ascase (1, 3, 5), or ranges:case (90:)means 90 or more andcase (75:89)means 75 to 89 inclusive.case defaultcatches everything else. Unlike C'sswitch, there is no fall-through.if (...) then ... else if (...) then ... else ... end ifis the general conditional (used inside the taxicab search). A single statement can also be guarded on one line:if (x < 0.0) x = 0.0.- Counted loops
do k = start, stop, stepmay count downwards with a negative step. The number of iterations is computed once, before the loop starts, so changingstopinside the loop has no effect, and you must never assign to the loop variable inside the body. do while (condition)repeats while the condition holds. An unconditionaldo ... end doloops forever until anexit.exitandcycleleave a loop or skip to its next iteration. By default they apply to the innermost loop; naming a loop, as insearch: do ... end do search, letscycle searchorexit searchact on an outer one. Herecycle searchabandons the inner loop as soon as the sum exceeds 1729, because largerbcan only make it bigger.advance='no'in awritestatement keeps the cursor on the same line, so several items can be printed in a loop; the emptyprint *then ends the line.
The search found both ways of writing 1729 as a sum of two cubes, the "taxicab number" from G. H. Hardy's famous anecdote about visiting Srinivasa Ramanujan in hospital: Hardy remarked that his taxi's number seemed rather dull, and Ramanujan replied that it was the smallest number expressible as a sum of two cubes in two different ways.
Putting it together: the day of the year
Here is a slightly larger program that combines logical expressions, select case with lists, and nested loops. It works out which day of the year a date is, taking the Gregorian leap-year rule into account:
! Day of the year, with leap years: logical expressions, select case lists and loops together
program day_of_year
implicit none
integer, parameter :: dates(3, 4) = reshape([ &
2024, 3, 1, & ! year, month, day
2025, 3, 1, &
1900, 12, 31, &
2000, 12, 31], [3, 4])
integer :: k, year, month, day, m, total
logical :: leap
do k = 1, size(dates, 2)
year = dates(1, k)
month = dates(2, k)
day = dates(3, k)
! Gregorian rule: every 4th year, except centuries, except every 400th year
leap = (mod(year, 4) == 0 .and. mod(year, 100) /= 0) .or. mod(year, 400) == 0
total = day
do m = 1, month - 1
select case (m)
case (4, 6, 9, 11)
total = total + 30
case (2)
if (leap) then
total = total + 29
else
total = total + 28
end if
case default
total = total + 31
end select
end do
print '(i4.4, "-", i2.2, "-", i2.2, ": day ", i3, ", leap year: ", l1)', year, month, day, total, leap
end do
end program day_of_yearIt prints:
2024-03-01: day 61, leap year: T
2025-03-01: day 60, leap year: F
1900-12-31: day 365, leap year: F
2000-12-31: day 366, leap year: TThe leap-year test is a single logical expression: a year divisible by 4 is a leap year unless it is divisible by 100, but years divisible by 400 are leap years after all, which is why 1900 was not one and 2000 was. The month lengths come from case (4, 6, 9, 11), a list of values, with February handled separately. Two new details: the dates table is built with reshape from a flat list into a 3 × 4 array, each column one date (lesson 3 is all about arrays), and the long reshape statement is continued over several lines with & at the end of each line. In the format, i4.4 and i2.2 print integers with leading zeros to a minimum number of digits, quoted text such as "-" appears literally, and l1 prints a logical as T or F.
Two more constructs are useful in larger programs. block (Fortran 2008) opens a nested scope where you can declare variables close to where they are used, and associate gives a short name to an expression:
block
real :: tmp ! exists only inside this block
tmp = a
a = b
b = tmp
end block
associate (v => state%velocity, dt => settings%time_step)
position = position + v * dt
end associateStyle that experienced Fortran programmers share
Fortran's syntax leaves a lot of room for personal taste, and old code shows every possible taste. Most modern projects, and the style guides published by the Fortran-lang community, converge on a few habits:
- Lowercase everything. Keywords, names and intrinsics in lowercase are easier to read than the all-capitals style inherited from card punches.
- Always use
::in declarations and always writeimplicit none. - Close every construct by name,
end do,end if,end select,end program day_of_year, and never use numbered labels withcontinueorgotoin new code. - Indent consistently, usually by two to four spaces per level. Free-form lines may be up to 132 characters long; a line ending in
&continues on the next, and a;separates two statements on one line (rarely a good idea). - Give constants names.
real, parameter :: g = 9.81documents the number and lets the compiler fold it into the code. - Declare loop variables and counters as
integerand keep them out of real arithmetic until you convert them deliberately withreal(...). - Prefer
select caseover longelse ifchains when testing one integer, character or logical value against several options.
None of these change what the program computes, but they make the difference between code a new colleague can maintain and code everyone is afraid to touch.
Traps
Misconception
"if (i <= n .and. a(i) > 0) is safe because .and. short-circuits." Fortran does not guarantee short-circuit evaluation. The compiler may evaluate both sides, in either order, so a(i) may be read even when i > n, out of bounds. Write nested if statements instead, or, with a Fortran 2023 compiler, a conditional expression. Compilers often do short-circuit in practice, which is what makes this bug so hard to find.
Misconception
"real(i / j) gives the exact quotient." The division inside the parentheses is integer division, done before the conversion. Convert first: real(i) / real(j).
Misconception
"Initialising a variable in its declaration sets it every time the procedure runs." In a procedure, integer :: calls = 0 gives calls the save attribute: it is set to 0 once, when the program starts, and keeps its value between calls. If you want a fresh value each time, assign it in an executable statement. Lesson 4 returns to this.
Misconception
"!= means not equal." In Fortran ! starts a comment, so if (a != b) is a syntax error at best. Not-equal is /=.
Exercises
1. Types, declarations and control flow
CoreComputationalWhat does print '(f0.1)', 7/2*2.0 print? (f0.1 prints a real with one decimal and no padding.)
2. Types, declarations and control flow
CoreComputationalWhat does print '(i0,1x,i0)', mod(-7, 3), modulo(-7, 3) print?
3. Types, declarations and control flow
Warm-upComputationalWhat is nint(-3.5)?
4. Types, declarations and control flow
CoreComputationalHow many times does the body of do k = 10, 1, -3 ... end do run?
5. Types, declarations and control flow
CoreComputationalWith character(len=10) :: s and s = 'abc', what does print '(i0,1x,i0)', len(s), len_trim(s) print?
6. Types, declarations and control flow
Warm-upComputationalIn the lesson's grading program, which grade does a mark of exactly 75 get?
select case (mark)
case (90:)
grade = 'A'
case (75:89)
grade = 'B'
case (50:74)
grade = 'C'
case default
grade = 'F'
end select
7. Types, declarations and control flow
StretchHumanAn array a has n elements. Why is if (i <= n .and. a(i) > 0.0) then a bug in portable Fortran?
8. Types, declarations and control flow
CoreComputationalWhat does print '(f0.1)', real(7/2) print?
Further reading and resources
- Fortran-lang, Quickstart tutorialThe community's introduction to variables, operators, control flow and arrays.
- GNU Fortran, intrinsic proceduresReference pages for every intrinsic, such as mod, modulo, nint, index and adjustl.
- ISO/IEC JTC1/SC22/WG5Draft standards, the authoritative description of every rule in this lesson.