!********o*********o*********o*********o*********o*********o*********o**
! This program computes numbers in the fibonacci sequence and tracks the
! ratio of successive numbers in the sequence.
!
! Method
!   As per problem 5, page 248 of Nyhoff & Leemstra's "Fortran 90 for
!   Engineers and Scientists", the fibonacci sequence is defined by the
!   recurrence relation
!     f(n) = f(n-1) + f(n-2)
!   with initial conditions
!     f(1) = 1
!     f(2) = 1
!   The method used is a straightforward implementation of the
!   recurrence relation.
!---------------------
! Inputs
!   howMany: The number of finbonacci numbers requested.
!
! Outputs
!   fn:      The nth fibonacci number.
!
! Other Variables
!   n:       Loop counter; current index into fibonacci sequence.
!   fn1:     The n-1st fibonacci number.
!   fn2:     The n-2nd fibonacci number.
!---------------------
! Author:   Bob Harris
! Class:    CMPSC 201F
! Section:  1234
! Date Due: 12 Oct 2003
!********o*********o*********o*********o*********o*********o*********o**

PROGRAM Fibonacci

IMPLICIT NONE

INTEGER :: howMany
INTEGER :: n, fn2, fn1, fn
REAL    :: ratio

! make the user specify how many fibonacci numbers she wants

PRINT *, "Pray tell, how many fibonacci numbers wouldst thou liketh to see?"
READ  *, howMany

IF (howMany <= 0) THEN
    PRINT *, "Don't you think that's rather pointless?"
ELSE
    ! print a header for our table

    PRINT *, "n   fib(n)   ratio"

    ! handle the first two values as a special case (for validity of the
    ! description of variables above, assume n is 3) and prepare for
    ! the first time into the loop

    fn2 = 1
    fn1 = 1

    IF (howMany >= 1) THEN
        PRINT *, 1,"    ",fn2,"    ","(none)"
    END IF

    IF (howMany >= 2) THEN
        ratio = REAL(fn2)/REAL(fn1)
        PRINT *, 1,"    ",fn1,"    ",ratio
    END IF

    ! generate any remaining values the user wants;  note that if
    ! howMany is less than 3, we will not go through the loop at all

    DO n=3,howMany

        ! compute the next fibonacci number, and the ratio

        fn = fn1 + fn2
        ratio = REAL(fn1)/REAL(fn)

        ! report progress to our user

        PRINT *, n,"    ",fn,"    ",ratio

        ! set things up for the next time through the loop

        fn2 = fn1
        fn1 = fn

    END DO
END IF

END PROGRAM Fibonacci

