next up previous contents
Next: Dynamic Data Structures Up: Examples and Exercises Previous: Interfaces and Generic Subprograms

Recursive Subprograms

Another area in which Fortran 77 has been extended is recursion. Although not possible in Fortran 77, Fortran 90 supports recursion. If a subprogram calls itself, directly or indirectly, the keyword recursive must appear in the subprogram statement.gif Recursive functions must also declare a result variable to avoid ambiguity with array-valued functions that are directly recursive. The result variable is used to hold the function result for each function invocation; the function name is used to invoke the function itself. Consequently, the recursive function's name should never appear on the left side of an assignment statement. An example of a recursive factorial function is shown below.

recursive function factorial( n ) result( f )
   integer f
   integer, intent( in ) :: n

   if ( n <= 0 ) then
      f = 1
   else
      f = n * factorial( n-1 )
   end if
end function factorial

exercise237

exercise244

exercise248

exercise251



next up previous contents
Next: Dynamic Data Structures Up: Examples and Exercises Previous: Interfaces and Generic Subprograms