Fortran Recursion
A recursive procedure calls itself, directly or indirectly. Many problems are naturally defined in terms of smaller versions of themselves: factorials, tree traversals, divide-and-conquer sorting, adaptive integration.
Declaring recursive procedures
Before Fortran 2018, a procedure had to be marked recursive to call itself. Since Fortran 2018 procedures are recursive by default, but writing recursive is still good style and keeps code portable to older compilers. A recursive function must use a result variable, because the function name refers to the function itself.
program factorials
use iso_fortran_env, only: int64
implicit none
integer :: n
do n = 0, 20, 5
print '(i2, a, i0)', n, '! = ', factorial(n)
end do
contains
recursive function factorial(n) result(f)
integer, intent(in) :: n
integer(int64) :: f
if (n <= 1) then
f = 1 ! base case
else
f = n * factorial(n - 1) ! recursive case
end if
end function factorial
end program factorials 0! = 1
5! = 120
10! = 3628800
15! = 1307674368000
20! = 2432902008176640000
Every recursive procedure needs a base case that stops the recursion. Without one, calls nest until the stack overflows and the program crashes.
Greatest common divisor
Euclid's algorithm is a two-line recursion:
program euclid
implicit none
print '(a, i0)', 'gcd(1071, 462) = ', gcd(1071, 462)
print '(a, i0)', 'gcd(17, 5) = ', gcd(17, 5)
print '(a, i0)', 'lcm(12, 18) = ', 12 * 18 / gcd(12, 18)
contains
recursive function gcd(a, b) result(g)
integer, intent(in) :: a, b
integer :: g
if (b == 0) then
g = a
else
g = gcd(b, mod(a, b))
end if
end function gcd
end program euclidgcd(1071, 462) = 21
gcd(17, 5) = 1
lcm(12, 18) = 36
Recursive subroutines: Tower of Hanoi
program hanoi
implicit none
integer :: moves
moves = 0
call move_disks(3, 'A', 'C', 'B', moves)
print '(a, i0)', 'total moves: ', moves
contains
recursive subroutine move_disks(n, from, to, via, moves)
integer, intent(in) :: n
character, intent(in) :: from, to, via
integer, intent(inout) :: moves
if (n == 0) return
call move_disks(n - 1, from, via, to, moves)
moves = moves + 1
print '(a, i0, 4a)', 'move disk ', n, ' from ', from, ' to ', to
call move_disks(n - 1, via, to, from, moves)
end subroutine move_disks
end program hanoimove disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C
total moves: 7
Divide and conquer: quicksort
Recursion shines with array sections. This quicksort partitions the array with pack and sorts each part recursively:
program quicksort_demo
implicit none
integer :: data(10) = [38, 27, 43, 3, 9, 82, 10, 3, 55, 21]
print '(*(i4))', quicksort(data)
contains
recursive function quicksort(a) result(sorted)
integer, intent(in) :: a(:)
integer :: sorted(size(a))
integer :: pivot
if (size(a) <= 1) then
sorted = a
return
end if
pivot = a(size(a) / 2)
sorted = [quicksort(pack(a, a < pivot)), &
pack(a, a == pivot), &
quicksort(pack(a, a > pivot))]
end function quicksort
end program quicksort_demo 3 3 9 10 21 27 38 43 55 82
This version is short and clear but creates many temporary arrays. Production code sorts in place, yet the structure (pick a pivot, split, recurse on each side) is the same.
Recursion vs. iteration
Recursive Fibonacci is the classic example of recursion done badly: fib(n) calls fib(n-1) and fib(n-2), which recompute the same values again and again. Counting the calls makes this visible:
program fib_calls
implicit none
integer :: calls, n, value
do n = 10, 25, 5
calls = 0
value = fib(n) ! call first, then print the counter
print '(a, i2, a, i6, a, i7, a)', 'fib(', n, ') = ', value, ' using ', calls, ' calls'
end do
contains
recursive function fib(n) result(f)
integer, intent(in) :: n
integer :: f
calls = calls + 1 ! host variable: counts every call
if (n < 2) then
f = n
else
f = fib(n - 1) + fib(n - 2)
end if
end function fib
end program fib_callsfib(10) = 55 using 177 calls
fib(15) = 610 using 1973 calls
fib(20) = 6765 using 21891 calls
fib(25) = 75025 using 242785 calls
The number of calls grows exponentially, while a simple loop needs only n steps. Use recursion when the problem has a branching structure that matches it (trees, divide and conquer), and loops for straight-line repetition.
Note: An internal procedure can read and change the variables of its host program, as
fibdoes withcalls. This is called host association. It's convenient for small programs but hides data flow, so prefer passing arguments in larger code. Notice that the program storesfib(n)invaluebefore printingcalls: a function with side effects should never be called in the same statement that also reads the variable it changes, because the evaluation order is not guaranteed.
Test yourself
Why must a recursive function use a result variable?
- For speed
- Because inside the function its name refers to the function itself (a call)
- Because recursive functions can't return integers
- It is optional and has no effect
What happens if a recursive procedure has no base case?
- It returns zero
- It recurses until the stack overflows
- The compiler adds one automatically
- It runs once
How many moves does Tower of Hanoi need for 4 disks?
- 8
- 15
- 16
- 7