PROGRAM MeanVariance
   IMPLICIT NONE
   INTEGER :: Number
   REAL    :: Data, Sum, Sum2
   REAL    :: Mean, Var, Std

   Number = 0
   Sum    = 0.0
   Sum2   = 0.0

   DO
     READ(*,*) Data
     Number = Number + 1
     WRITE(*,*) 'Data item ', Number,' = ', Data
     CALL Sums(Data, Sum, Sum2)
   END DO

   CALL Results(Sum, Sum2, Number, Mean, Var, Std)
   CALL PrintResult(Number, Mean, Var, Std)

CONTAINS
   SUBROUTINE Sums(x, Sum, SumSQR)
      IMPLICIT NONE
      REAL, INTENT(IN)    :: x
      REAL, INTENT(INOUT) :: Sum, SumSQR
      Sum = Sum + x
      SumSQR = SumSQR + x*x
   END SUBROUTINE Sums

   SUBROUTINE Results(Sum, SumSQR, n, Mean, Variance, StdDev)
      IMPLICIT NONE
      INTEGER, INTENT(IN)    :: n
      REAL, INTENT(IN)       :: Sum, SumSQR
      REAL, INTENT(OUT)      :: Mean, Variance, StdDev

      Mean = Sum / n
      Variance = ( SumSQR - Sum * Sum / REAL(n) ) / REAL( n - 1 )
      StdDev = SQRT(Variance)
   END SUBROUTINE Results

   SUBROUTINE PrintResults(n, Mean, Variance, StdDev)
      IMPLICIT NONE
      INTEGER, INTENT(IN)     :: n
      REAL, INTENT(IN)        :: Mean, Variance, StdDev

      WRITE(*,*)
      WRITE(*,*) 'No. of data items  = ', n
      WRITE(*,*) 'Mean               = ', Mean
      WRITE(*,*) 'Variance           = ', Variance
      WRITE(*,*) 'Standard Deviation = ', StdDev
   END SUBROUTINE PrintResults

END PROGRAM MeanVariance
