Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Fortran Practice Problems with Solutions

Ten Fortran exercises on procedures, modules, derived types, file I/O and numerical methods, each with hints, a full solution and a runnable Python check.

Reading code teaches less than writing it. These ten exercises revisit the chapter: procedures and modules, derived types and pointers, file I/O and formatting, and numerical and parallel ideas. Try each one yourself before opening the solution. Compile with gfortran -Wall -Wextra -fcheck=all -g: the flags catch out-of-bounds indices and uninitialized variables, the commonest beginner errors.

Fortran is not runnable in the browser, so the solutions are read-only. For several problems a Python stand-in produces the expected answer so you can compare it with your own program's output.

How to use this page

  1. Read the statement and sketch the procedure signatures (with intent).
  2. Write and test small pieces. Print intermediate values.
  3. Compare with the hint, and only then the solution.
  4. Extend the problem (the last line of each one).

1. Swap and sort

Task. Write subroutine swap(a, b) for reals and use it in a bubble_sort(x) subroutine that sorts an array into ascending order.

Hint. Compare neighbors; after each pass the largest element is in place. Stop early if a pass makes no swap.

FORTRAN
module sort_mod
  implicit none
contains
  subroutine swap(a, b)
    real, intent(inout) :: a, b
    real :: t
    t = a; a = b; b = t
  end subroutine swap

  subroutine bubble_sort(x)
    real, intent(inout) :: x(:)
    integer :: n, i
    logical :: swapped
    n = size(x)
    do
      swapped = .false.
      do i = 1, n - 1
        if (x(i) > x(i + 1)) then
          call swap(x(i), x(i + 1))
          swapped = .true.
        end if
      end do
      n = n - 1
      if (.not. swapped .or. n < 2) exit
    end do
  end subroutine bubble_sort
end module sort_mod

Extend: make it generic for integers and reals (see interfaces and generic procedures).

2. Primes by sieve

Task. Print all primes up to n = 50 with the sieve of Eratosthenes using a logical array and whole-array operations.

Hint. Start with all .true.; for each prime p mark p*p, p*p + p, ... as .false.. A section is_prime(p*p::p) = .false. does this in one statement.

FORTRAN
program sieve
  implicit none
  integer, parameter :: n = 50
  logical :: is_prime(n)
  integer :: p, i

  is_prime = .true.
  is_prime(1) = .false.
  do p = 2, int(sqrt(real(n)))
    if (is_prime(p)) is_prime(p*p::p) = .false.
  end do
  print "(*(i0, 1x))", pack([(i, i = 1, n)], is_prime)
end program sieve

pack collects the indices where the mask is true. The expected output is shown by the stand-in below.

Python Check: primes up to 50

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extend: count primes below one million and time it.

3. Recursive greatest common divisor and least common multiple

Task. Write recursive function gcd(a, b) and lcm(a, b) built on it.

Hint. gcd(a, b) = gcd(b, mod(a, b)), and lcm = a / gcd * b (divide first to avoid overflow).

FORTRAN
recursive function gcd(a, b) result(g)
  integer, intent(in) :: a, b
  integer :: g
  if (b == 0) then
    g = abs(a)
  else
    g = gcd(b, mod(a, b))
  end if
end function gcd

integer function lcm(a, b)
  integer, intent(in) :: a, b
  lcm = a / gcd(a, b) * b
end function lcm

Extend: make gcd accept an array and reduce over it.

4. Matrix utilities

Task. For a 3 by 3 matrix, compute the transpose, the trace (sum of the diagonal) and check whether the matrix is symmetric, using intrinsics only.

FORTRAN
real :: a(3, 3) = reshape([1, 2, 3,  2, 5, 6,  3, 6, 9], [3, 3])
real :: t(3, 3), tr
integer :: i

t = transpose(a)
tr = sum([(a(i, i), i = 1, 3)])
print *, "trace:", tr                      ! 15.0
print *, "symmetric:", all(a == t)         ! T

The trace is 1 + 5 + 9 = 15, and this matrix equals its transpose. Extend: find the largest off-diagonal element with maxval and a mask built from row and column indices.

5. Derived type: student records

Task. Define type student with a name and five scores. Write a function average(s) and print the students sorted by average.

Hint. An array of student, a pure function, and the index sort from problem 1 applied to the average values. Remember % for component access (derived types).

FORTRAN
type :: student
  character(len=20) :: name
  real :: scores(5)
end type student

pure function average(s) result(m)
  type(student), intent(in) :: s
  real :: m
  m = sum(s%scores) / size(s%scores)
end function average

Extend: add a type-bound procedure s%grade() returning a letter (type-bound procedures).

6. Newton's method for a square root

Task. Compute sqrt(2) by iterating x = 0.5 * (x + a / x) until the change is below 1e-12, and report the number of iterations.

FORTRAN
function newton_sqrt(a) result(x)
  real(8), intent(in) :: a
  real(8) :: x, xold
  integer :: it
  x = max(a, 1.0d0)
  do it = 1, 100
    xold = x
    x = 0.5d0 * (x + a / x)
    if (abs(x - xold) < 1.0d-12) exit
  end do
end function newton_sqrt
Python Check: Newton iterations for sqrt(2)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extend: generalize to any function and its derivative with a procedure(fn) argument.

7. Numerical integration with Simpson's rule

Task. Integrate sin(x) from 0 to pi with Simpson's rule on n = 100 intervals (n even). The exact answer is 2.

Hint. Weights 1, 4, 2, 4, ..., 4, 1 times h/3.

Python Check: Simpson's rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

FORTRAN
function simpson(f, a, b, n) result(s)
  procedure(fn) :: f                ! fn is an abstract interface (see the interfaces lesson)
  real(8), intent(in) :: a, b
  integer, intent(in) :: n
  real(8) :: s, h
  integer :: i
  h = (b - a) / n
  s = f(a) + f(b)
  do i = 1, n - 1
    if (mod(i, 2) == 1) then
      s = s + 4.0d0 * f(a + i * h)
    else
      s = s + 2.0d0 * f(a + i * h)
    end if
  end do
  s = s * h / 3.0d0
end function simpson

Extend: parallelize with an OpenMP reduction(+:s) (OpenMP in Fortran).

8. Count lines and sum a column

Task. Read data.txt (two numbers per line), report the line count and the sum of each column, handling a missing file and bad lines gracefully.

Hint. open with iostat, a loop read (u, *, iostat=ios) a, b, exit on ios /= 0, and distinguish iostat_end from errors (file I/O basics).

Extend: write the totals to summary.txt with a format that aligns the numbers (formatted output).

9. Linked list reversal

Task. Build a list of integers 1 to 5 with a pointer-based node type and reverse it in place by re-pointing next.

Hint. Keep three pointers: prev, cur, nxt. For each node: save nxt => cur%next, set cur%next => prev, then advance both (pointers and targets).

FORTRAN
subroutine reverse(head)
  type(node), pointer :: head
  type(node), pointer :: prev, cur, nxt
  prev => null()
  cur => head
  do while (associated(cur))
    nxt => cur%next
    cur%next => prev
    prev => cur
    cur => nxt
  end do
  head => prev
end subroutine reverse

Extend: free the list without leaks and verify the order with a printing routine.

10. A tiny physics step

Task. Simulate a ball thrown upward at 20 m/s under gravity 9.81 m/s2 with time step 0.01 s until it lands. Print the maximum height and the flight time.

Hint. The exact values are v0**2 / (2 g) and 2 v0 / g, so you can compare: the maximum height is about 20.39 m and the flight time about 4.08 s, with small Euler errors that shrink as you reduce dt.

Python Check: the exact answers and an Euler run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extend: add drag proportional to v**2, and compare Euler with a velocity Verlet step.

Where to go next

If you can solve most of these without peeking, you are ready for real programs. Good next steps are porting a program you already have from Python or MATLAB, reading open source Fortran such as parts of LAPACK or the stdlib project, using fpm (the Fortran package manager) to organize a project, and calling a library such as BLAS, FFTW or NetCDF from the C interoperability techniques.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which compiler flags help catch out-of-bounds and uninitialized errors while learning?

    Warnings plus runtime checks reveal most beginner mistakes. Remove -fcheck for production speed.
  2. 2. In the sieve, what does pack([(i, i = 1, n)], is_prime) produce?

    pack selects the elements of the first array where the mask is true.
  3. 3. Why does lcm divide before multiplying?

    a / gcd(a, b) * b gives the same result with a smaller intermediate value.
  4. 4. What does Euler integration of the thrown ball do relative to the exact answer?

    A first-order scheme has an error proportional to the step size.

Summary

  • Practice with small, checkable programs: sorting, sieves, recursion, matrices, records, root finding, integration, file reading, pointers and simulation.
  • Compile with warnings and run-time checks while learning.
  • Verify each solution against a known value or an independent calculation.
  • Extend every exercise: generic versions, parallel versions and tests teach the most.

Next: back to the Fortran track