The oldest major programming language still in active use (1957) โ its raw numerical performance keeps it running weather forecasting models, computational physics, and supercomputer simulations that newer languages haven't displaced. Copy-paste examples plus live Run/Submit exercises.
program hello
print *, 'Hello, world!'
end program hello
.f90) doesn't need the old fixed-column layout โ this cheat sheet uses that modern style throughout.program vars
integer :: age = 25
real :: price = 19.99
character(len=10) :: name = 'Sam'
print *, age, price, name
end program vars
integer :: age = 20
if (age >= 18) then
print *, 'Adult'
else if (age >= 13) then
print *, 'Teen'
else
print *, 'Child'
end if
integer :: i, n
do i = 1, 5
print *, i
end do
n = 3
do while (n > 0)
print *, n
n = n - 1
end do
Fortran arrays are 1-indexed by default and built for fast numerical operations on whole arrays at once.
integer :: nums(5) = [10, 20, 30, 40, 50]
print *, nums(1) ! 10 (1-indexed!)
print *, sum(nums) ! 150 โ whole-array operations are built in
function add(a, b) result(total)
integer :: a, b, total
total = a + b
end function add
Full runnable programs, compiled and run in a real Fortran (gfortran) sandbox โ same workspace as the other cheat sheets.
program sumarr
integer :: nums(6) = [4, 8, 15, 16, 23, 42]
print *, sum(nums)
end program sumarr
program revstr
character(len=7) :: s = 'fortran'
character(len=7) :: r
integer :: i
do i = 1, 7
r(i:i) = s(8-i:8-i)
end do
print *, r
end program revstr
program fizzbuzz
integer :: i
do i = 1, 15
if (mod(i, 15) == 0) then
print *, 'FizzBuzz'
else if (mod(i, 3) == 0) then
print *, 'Fizz'
else if (mod(i, 5) == 0) then
print *, 'Buzz'
else
print *, i
end if
end do
end program fizzbuzz
program stats
real :: nums(5) = [4.0, 8.0, 15.0, 16.0, 23.0]
real :: avg, variance
integer :: i
avg = sum(nums) / size(nums)
variance = 0.0
do i = 1, size(nums)
variance = variance + (nums(i) - avg)**2
end do
variance = variance / size(nums)
print *, 'avg=', avg, 'stddev=', sqrt(variance)
end program stats