Recursion in Fortran
Our example demonstrates recursive functions in Fortran. Here’s a classic example.
In this Fortran version:
We define a module
recursion_module
to contain our recursive functions.The
fact
function is defined as recursive. It calculates the factorial of a number using recursion.The
fib
function is also defined as recursive. It calculates the Fibonacci number using recursion.In the main program, we use the module and call both functions with an argument of 7.
To run the program, save it as recursion.f90
and compile it using a Fortran compiler:
Note that in Fortran, we use the recursive
keyword to explicitly declare a function as recursive. Unlike Go, Fortran doesn’t have closures, so we implement the Fibonacci function as a separate recursive function rather than a closure.
Fortran’s strong typing and explicit recursion declarations make it well-suited for scientific and numerical computations where recursion might be used in complex algorithms.