For a general introduction to recursion (in C++) see this link.
Note that recursion is not implemented in older versions of FORTRAN!
The following is an example of the recursive Towers of Hanoi code implemented in Fortran-90. (It is also available for downloading at this link.)
program hanoimain ! recursive towers of hanoi program in ! fortran 90 integer n n = 5 call hanoi(n,'a','c','b') end ! recursive subroutine hanoi(n,frompeg,auxpeg,topeg) integer n character*1 frompeg,auxpeg,topeg if (n == 1) then write(6,*)"Move disk 1 from peg ", frompeg, " to peg ", topeg else call hanoi(n-1,frompeg,auxpeg,topeg) write(6,101) n, frompeg,topeg 101 FORMAT(1x,"Move disk ",i1," from peg ", A1, " to peg ", A1) call hanoi(n-1,auxpeg,topeg,frompeg) endif end
As in other languages, the recursive FUNCTION can be called on the right side of an assignment statement within the FUNCTION. The RESULT variable must be given a return value somewhere within the code.
(Recall that in a non-recursive Fortran FUNCTION, the return value is assigned to the name of the FUNCTION which is considered a local variable within the subprogram. In a recursive FUNCTION, the FUNCTION name retains its purpose as a means to invoke itself, and so another identifier must be designated as the means to return the value computed by the subprogram.)
FUNCTIONS designated as recursive as then used as they would be in other languages.
The following is an example of a recursive fibonacci function implemented in Fortran-90. (It is also available for downloading at this link.)
program fibonmain ! recursive fibonacci program in ! fortran 90 integer n, final, fibon n = 5 final = fibon(n) write(6,*) "Final fibonacci value for input of",n," is",final end ! recursive function fibon(n) result (fib_result) integer :: n, fib_result if (n <= 2) then fib_result = 1 else fib_result = fibon(n-1) + fibon(n-2) endif end
This page is maintained by Dennis C. Smolarski, S.J.
dsmolarski@scuacc.scu.edu
© Copyright 1998 Dennis C. Smolarski, SJ, All rights reserved.
Last changed: 9 April 1998.