๐Ÿงฎ

Fortran Cheat Sheet

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.

Jump to: Your first programVariablesif / else LoopsArraysSubroutines & functions ๐Ÿš€ Practice problems

Your first program

program hello
    print *, 'Hello, world!'
end program hello
๐Ÿ“ Modern free-form Fortran (.f90) doesn't need the old fixed-column layout โ€” this cheat sheet uses that modern style throughout.

Variables

program vars
    integer :: age = 25
    real :: price = 19.99
    character(len=10) :: name = 'Sam'
    print *, age, price, name
end program vars

if / else

integer :: age = 20
if (age >= 18) then
    print *, 'Adult'
else if (age >= 13) then
    print *, 'Teen'
else
    print *, 'Child'
end if

Loops

integer :: i, n
do i = 1, 5
    print *, i
end do

n = 3
do while (n > 0)
    print *, n
    n = n - 1
end do

Arrays

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

Subroutines & functions

function add(a, b) result(total)
    integer :: a, b, total
    total = a + b
end function add

๐Ÿš€ Practice problems

Full runnable programs, compiled and run in a real Fortran (gfortran) sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

program sumarr
    integer :: nums(6) = [4, 8, 15, 16, 23, 42]
    print *, sum(nums)
end program sumarr

Reverse a string MEDIUM

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

FizzBuzz MEDIUM

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

Average and standard deviation HARD

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