Fortran Exercises
Time to practise! Each exercise has a starter program that compiles and runs as-is, printing a placeholder result so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but give it a few minutes first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Temperature table | do loops, formats |
| 2 | Digit statistics | integer division, mod, do while |
| 3 | FizzBuzz | if/select case, mod, non-advancing output |
| 4 | Vector statistics | array intrinsics, masks |
| 5 | Matrix trace and symmetry | 2-D arrays, transpose, all |
| 6 | Word counter | strings, index, adjustl |
| 7 | Prime sieve | logical arrays, sections, pack |
| 8 | A fraction type |
modules, derived types, operator overloading |
1. Temperature table
Print a Celsius → Fahrenheit table for −20, −10, …, 40 °C using F = C × 9/5 + 32. Each row should look like -20 C = -4.0 F (Celsius as i5, Fahrenheit as f7.1).
Expected first and last lines: -20 C = -4.0 F and 40 C = 104.0 F.
program temperature_table
implicit none
integer :: c
real :: f
! TODO: loop over -20, -10, ..., 40 and use the formula
c = 0
f = 0.0
print '(i5, a, f7.1, a)', c, ' C = ', f, ' F'
end program temperature_table 0 C = 0.0 F
Show solution
program temperature_table
implicit none
integer :: c
real :: f
do c = -20, 40, 10
f = c * 9.0 / 5.0 + 32.0
print '(i5, a, f7.1, a)', c, ' C = ', f, ' F'
end do
end program temperature_tableNote 9.0 / 5.0: with 9 / 5 the integer division would give 1.
2. Digit statistics
For n = 9081726354, print how many digits it has and the sum of its digits. The number doesn't fit a default integer, so use int64.
Expected: digits: 10 and digit sum: 45.
program digit_stats
use iso_fortran_env, only: int64
implicit none
integer(int64) :: n
integer :: count, total
n = 9081726354_int64
count = 0
total = 0
! TODO: repeatedly take the last digit with mod(n, 10) and divide n by 10
print '(a, i0)', 'digits: ', count
print '(a, i0)', 'digit sum: ', total
end program digit_statsdigits: 0
digit sum: 0
Show solution
program digit_stats
use iso_fortran_env, only: int64
implicit none
integer(int64) :: n
integer :: count, total
n = 9081726354_int64
count = 0
total = 0
do while (n > 0)
total = total + int(mod(n, 10_int64))
n = n / 10
count = count + 1
end do
print '(a, i0)', 'digits: ', count
print '(a, i0)', 'digit sum: ', total
end program digit_stats3. FizzBuzz
For 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise, all on one line separated by spaces.
Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
program fizzbuzz
implicit none
integer :: i
do i = 1, 15
! TODO: choose between Fizz, Buzz, FizzBuzz and the number
write(*, '(i0, 1x)', advance='no') i
end do
print *
end program fizzbuzz1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
program fizzbuzz
implicit none
integer :: i
do i = 1, 15
select case (mod(i, 15))
case (0)
write(*, '(a, 1x)', advance='no') 'FizzBuzz'
case (3, 6, 9, 12)
write(*, '(a, 1x)', advance='no') 'Fizz'
case (5, 10)
write(*, '(a, 1x)', advance='no') 'Buzz'
case default
write(*, '(i0, 1x)', advance='no') i
end select
end do
print *
end program fizzbuzzSelecting on mod(i, 15) handles all four cases with one select case.
4. Vector statistics
For the data below, print the mean, the (population) standard deviation sqrt(mean((x - mean)**2)), the number of values above the mean, and the largest value below 10, without writing any loop.
Expected:
mean: 8.250
std: 4.943
above: 4
max<10: 9.0program vector_stats
implicit none
real :: x(8) = [4.0, 9.0, 15.0, 2.0, 7.0, 16.0, 3.0, 10.0]
real :: mean, std
integer :: above
real :: max_small
! TODO: use sum, size, count, maxval with mask=
mean = 0.0
std = 0.0
above = 0
max_small = 0.0
print '(a, f7.3)', 'mean: ', mean
print '(a, f7.3)', 'std: ', std
print '(a, i2)', 'above: ', above
print '(a, f3.1)', 'max<10: ', max_small
end program vector_statsmean: 0.000
std: 0.000
above: 0
max<10: 0.0
Show solution
program vector_stats
implicit none
real :: x(8) = [4.0, 9.0, 15.0, 2.0, 7.0, 16.0, 3.0, 10.0]
real :: mean, std
integer :: above
real :: max_small
mean = sum(x) / size(x)
std = sqrt(sum((x - mean)**2) / size(x))
above = count(x > mean)
max_small = maxval(x, mask=x < 10.0)
print '(a, f7.3)', 'mean: ', mean
print '(a, f7.3)', 'std: ', std
print '(a, i2)', 'above: ', above
print '(a, f3.1)', 'max<10: ', max_small
end program vector_stats5. Matrix trace and symmetry
Build the 4×4 matrix with elements a(i, j) = i * j + abs(i - j), then print its trace (the sum of the diagonal) and whether it is symmetric.
Expected: trace = 30 and symmetric: T.
program matrix_check
implicit none
integer, parameter :: n = 4
integer :: a(n, n), i, j, trace
logical :: symmetric
! TODO: fill a, compute the trace and test symmetry with transpose
a = 0
trace = 0
symmetric = .false.
print '(a, i0)', 'trace = ', trace
print '(a, l1)', 'symmetric: ', symmetric
end program matrix_checktrace = 0
symmetric: F
Show solution
program matrix_check
implicit none
integer, parameter :: n = 4
integer :: a(n, n), i, j, trace
logical :: symmetric
do j = 1, n
do i = 1, n
a(i, j) = i * j + abs(i - j)
end do
end do
trace = sum([(a(i, i), i = 1, n)])
symmetric = all(a == transpose(a))
print '(a, i0)', 'trace = ', trace
print '(a, l1)', 'symmetric: ', symmetric
end program matrix_checkThe diagonal elements are i², so the trace is 1 + 4 + 9 + 16 = 30.
6. Word counter
Write a function word_count(text) that returns the number of blank-separated words in a string (multiple blanks count as one separator).
Expected: 5 for ' Fortran is fast and fun ' and 0 for ' '.
program words
implicit none
print '(i0)', word_count(' Fortran is fast and fun ')
print '(i0)', word_count(' ')
contains
integer function word_count(text)
character(len=*), intent(in) :: text
! TODO: count the positions where a non-blank follows a blank (or the start)
word_count = -1
end function word_count
end program words-1
-1
Show solution
program words
implicit none
print '(i0)', word_count(' Fortran is fast and fun ')
print '(i0)', word_count(' ')
contains
integer function word_count(text)
character(len=*), intent(in) :: text
integer :: i
logical :: in_word
word_count = 0
in_word = .false.
do i = 1, len(text)
if (text(i:i) /= ' ') then
if (.not. in_word) word_count = word_count + 1
in_word = .true.
else
in_word = .false.
end if
end do
end function word_count
end program words7. Prime sieve
Use the sieve of Eratosthenes: start with a logical array is_prime(2:n) set to .true., and for each prime p mark its multiples p*p, p*p+p, … as .false. with a strided section. Then print the primes up to 60 with pack.
Expected: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 and 17 primes.
program sieve
implicit none
integer, parameter :: n = 60
logical :: is_prime(2:n)
integer :: i
is_prime = .true.
! TODO: cross out the multiples of each prime p with p*p <= n
print '(*(i0, 1x))', pack([(i, i = 2, n)], is_prime)
print '(i0, a)', count(is_prime), ' primes'
end program sieve2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
59 primes
Show solution
program sieve
implicit none
integer, parameter :: n = 60
logical :: is_prime(2:n)
integer :: i, p
is_prime = .true.
do p = 2, int(sqrt(real(n)))
if (is_prime(p)) is_prime(p*p:n:p) = .false.
end do
print '(*(i0, 1x))', pack([(i, i = 2, n)], is_prime)
print '(i0, a)', count(is_prime), ' primes'
end program sieveThe section is_prime(p*p:n:p) selects every p-th element starting at p², so a single assignment crosses out all the multiples.
8. A fraction type
Complete the module: a fraction type with integer components num and den, a function reduce that divides both by their gcd, and an overloaded + operator. Adding 1/6 + 1/3 should print 1/2, and 3/4 + 5/6 should print 19/12.
module fractions
implicit none
type :: fraction
integer :: num, den
end type fraction
! TODO: add an interface operator(+) that uses add_fractions
contains
pure recursive integer function gcd(a, b) result(g)
integer, intent(in) :: a, b
if (b == 0) then
g = abs(a)
else
g = gcd(b, mod(a, b))
end if
end function gcd
pure function reduce(f) result(r)
type(fraction), intent(in) :: f
type(fraction) :: r
r = f ! TODO: divide num and den by gcd(num, den)
end function reduce
pure function add_fractions(a, b) result(c)
type(fraction), intent(in) :: a, b
type(fraction) :: c
c = fraction(a%num * b%den + b%num * a%den, a%den * b%den)
c = reduce(c)
end function add_fractions
end module fractions
program use_fractions
use fractions
implicit none
type(fraction) :: s
s = add_fractions(fraction(1, 6), fraction(1, 3)) ! TODO: write fraction(1, 6) + fraction(1, 3)
print '(i0, "/", i0)', s
s = add_fractions(fraction(3, 4), fraction(5, 6))
print '(i0, "/", i0)', s
end program use_fractions9/18
38/24
Show solution
module fractions
implicit none
type :: fraction
integer :: num, den
end type fraction
interface operator(+)
module procedure add_fractions
end interface
contains
pure recursive integer function gcd(a, b) result(g)
integer, intent(in) :: a, b
if (b == 0) then
g = abs(a)
else
g = gcd(b, mod(a, b))
end if
end function gcd
pure function reduce(f) result(r)
type(fraction), intent(in) :: f
type(fraction) :: r
integer :: g
g = gcd(f%num, f%den)
r = fraction(f%num / g, f%den / g)
end function reduce
pure function add_fractions(a, b) result(c)
type(fraction), intent(in) :: a, b
type(fraction) :: c
c = fraction(a%num * b%den + b%num * a%den, a%den * b%den)
c = reduce(c)
end function add_fractions
end module fractions
program use_fractions
use fractions
implicit none
type(fraction) :: s
s = fraction(1, 6) + fraction(1, 3)
print '(i0, "/", i0)', s
s = fraction(3, 4) + fraction(5, 6)
print '(i0, "/", i0)', s
end program use_fractionsTest yourself
In exercise 7, which elements does is_prime(9:60:3) select?
- Elements 9 to 60
- Every third element from 9: 9, 12, 15, …, 60
- Elements 3, 6, 9
- The multiples of 9
Why does exercise 2 write mod(n, 10_int64)?
modrequires both arguments to have the same kind- 10 is too large for a default integer
- It makes the loop faster
- It is optional style
What does print '(i0, "/", i0)', s print for a fraction variable s?
- Nothing; derived types can't be printed
- Its two integer components separated by a slash
- The type name
- The memory address