PROGRAM avg4

IMPLICIT NONE

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

! This version uses file input
!   and we also play with formatting

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(IOSTAT=ierr,UNIT=11,FMT=*) x
   IF(ierr /= 0) EXIT
   avg = avg + x
   n = n + 1
ENDDO

CLOSE(11)

WRITE(12,*)'the number of numbers averaged is ',n
WRITE(12,'(a40,i1)')'the number of numbers averaged is ',n
WRITE(12,'(a40,i10)')'the number of numbers averaged is ',n
WRITE(12,'(a40,i10.8)')'the number of numbers averaged is ',n

WRITE(12,*)'the average is : ',avg / n
WRITE(12,'(a40,f8.4)')'the average is : ',avg / n
WRITE(12,'(a40,f5.4)')'the average is : ',avg / n
WRITE(12,'(a40,e11.4)')'the average is : ',avg / n
WRITE(12,'(e11.4)')avg / n, avg
WRITE(12,202)'the average is : ',avg / n

202  FORMAT(a40,e11.4)




END PROGRAM avg4
