Fibonacci numbers (FORTRAN)

From LiteratePrograms
Jump to: navigation, search
Other implementations: ALGOL 68 | Alice ML | BaCon | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Prolog | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by


 F(n) =
 \begin{cases}
   0             & n = 0 \\
   1             & n = 1 \\
   F(n-1)+F(n-2) & n > 1 \\
  \end{cases} .

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


[edit] Implementation

The [fibonacci] numbers in FORTRAN:

<<fib.f90>>=
program main
  implicit none
  interface 
     function fib(n)
       integer, intent(in) :: n 
       integer :: fib
     end function fib
  end interface

  print *, fib(10)
end program main

recursive function fib (n)  result (fnum) 
  integer, intent(in)  :: n
  integer :: fnum
  if (n<2) then 
     fnum = n
  else
     fnum = fib(n-1) + fib(n-2)
  endif
end function fib
Download code
hijacker
hijacker
hijacker
hijacker