PROGRAM Frequency_Distribution_1
!-----------------------------------------------------------------------
! Program to generate a frequency distribution of the number of 1-hour
! periods in which there were 0, 1, 2, ... defective parts produced by
! a machine.  The data is read from a file.  Identifiers used are:
!     MaxDefective : parameter representing maximum # of defective 
!                    parts
!     Count        : Count(I) = # of 1-hour periods with I defective
!                    parts
!     NumDefects   : number of defective parts read from file
!     FileName     : name of the data file
!     End_of_File  : end-of-file indicator
!     I            : subscript 
!
! Input (keyboard): FileName
! Input (file):     Number of defects per hour
! Output:           Frequency distribution -- elements of array Count
!-----------------------------------------------------------------------

  IMPLICIT NONE
  INTEGER, PARAMETER :: MaxDefective = 5
  INTEGER, DIMENSION(0:MaxDefective) :: Count = 0
  INTEGER :: NumDefects, I, End_of_File
  CHARACTER(20) :: FileName

  ! Get file name, open the file as unit 15

  WRITE (*, '(1X, A)', ADVANCE = "NO") "Enter name of data file: "
  READ *, FileName
  OPEN (UNIT = 15, FILE = FileName, STATUS = "OLD")

  ! While there is more data, read # of defective parts and
  ! increment appropriate counter

  DO
     READ (15, *, IOSTAT = End_of_File) NumDefects
     IF (End_of_File < 0) EXIT
     ! If end of file reached, terminate repetition
 
     ! Otherwise continue with the following
     NumDefects = MIN(NumDefects, MaxDefective)
     Count(NumDefects) = Count(NumDefects) + 1
  END DO

  ! Print the frequency distribution

  PRINT *
  PRINT *, "# of defectives   # of hours"
  PRINT *, "===============   =========="
  DO I = 0, MaxDefective
     PRINT '(1X, I8, I15)', I, Count(I)
  END DO

  CLOSE (15)

END PROGRAM Frequency_Distribution_1
