Example F Program--Factorials

module factorial_demo

public :: factorial

logical, save, public :: debug = .false.


recursive function factorial (n) result (r)

integer, intent (in) :: n
integer              :: r

if ( debug ) then
  print *, "Entering factorial with n = ", n
end if

select case (n)
case (:-1)
  print *, "Bad value for n ", n
case (0, 1)
  r = 1
case (2:)
  r = n*factorial(n-1)
end select

if (debug) then
  print *, "Leaving factorial for n= ", n, ", n! = ", r
end if

end function factorial

end module factorial_demo

program try_fact
use factorial_demo

integer           :: n, v
character(len=1)  :: d

outer: do
  print *, "Enter a number"
  read *, n
  print *, "Do you want to debug?"
  do  ! Look for Yes, No, or Quit
    read *, d
    select case (d)
    case ("Y", "y")
      debug = .true.
    case ("N", "n")
      debug = .false.
    case ("Q", "q")
      exit outer
    case default
      print *, "Enter `yes', `no' or `quit'!"
    end select
  end do
v = factorial(n)
print "(i5, a, i15)", n, "! = ", v

end do outer

end program try_fact

Back to F Example Codes Page

Back to F Homepage

Questions or Comments?