PROGRAM avg3

IMPLICIT NONE

! A program to average an arbitrarily long list of numbers.

! This version uses multiple file streams, 
!   with file open, close and inquire functions.

INTEGER :: n, ierr
REAL :: x, avg
CHARACTER(LEN=20) :: input_file
LOGICAL :: l_exist

WRITE(*,*)'enter input file name'
READ(*,*)input_file

INQUIRE(FILE=TRIM(input_file),EXIST=l_exist)
IF(.NOT. l_exist) STOP 'file does not exist'
OPEN(UNIT=11,FILE=TRIM(input_file),FORM='formatted',STATUS='OLD',ACTION='READ')

avg = 0.
n = 0

DO 
   READ(11,*,IOSTAT=ierr) x
   IF(ierr /= 0) EXIT
   avg = avg + x
   n = n + 1
ENDDO

CLOSE(11)

WRITE(12,*)'the average is : ',avg / n

END PROGRAM avg3
