PROGRAM Least_Squares_Line
!----------------------------------------------------------------------
! Program to find the equation of the least-squares line for a set 
! of data points.  Identifiers used are:
!   X, Y             : (X,Y) is the observed data point
!   EndDataFlag      : end-of-data flag (parameter) 
!   NumPoints        : number of data points
!   Sum_of_X         : sum of the Xs 
!   Sum_of_X_squared : sum of the squares of the Xs 
!   Sum_of_Y         : sum of the Ys 
!   Sum_of_XY        : sum of the products X*Y
!   X_Mean           : mean of the Xs 
!   Y_Mean           : mean of the Ys 
!   Slope            : slope of least-squares line 
!   Y_Intercept      : y-intercept of the line 
!
! Input:  A collection of data points 
! Output: The equation of the least-squares line 
!----------------------------------------------------------------------

  IMPLICIT NONE
  INTEGER :: NumPoints
  REAL :: X, Y, Sum_of_X, Sum_of_X_squared, Sum_of_Y, Sum_of_XY,&
          X_Mean, Y_Mean, Slope, Y_Intercept
  REAL, PARAMETER :: EndDataFlag = -99.0

  ! Initialize counter and the sums to 0 and read first data point

  NumPoints = 0
  Sum_of_X = 0.0
  Sum_of_X_squared = 0.0
  Sum_of_Y = 0.0
  Sum_of_XY = 0.0
  PRINT *, "To stop, enter", EndDataFlag, " for coordinates of point."

  ! Repeat the following:
  DO
     WRITE (*, '(1X, A)', ADVANCE = "NO") "Enter point: "
     READ *, X, Y

     ! If end of data, terminate repetition.
	  IF ((X == EndDataFlag) .OR. (Y == EndDataFlag)) EXIT

     ! Otherwise continue with the following
     NumPoints = NumPoints + 1
     Sum_of_X = Sum_of_X + X
     Sum_of_X_squared = Sum_of_X_squared + X ** 2
     Sum_of_Y = Sum_of_Y + Y
     Sum_of_XY = Sum_of_XY + X * Y
  END DO

  ! Find equation of least-squares line

  X_Mean = Sum_of_X / NumPoints
  Y_Mean = Sum_of_Y / NumPoints
  Slope = (Sum_of_XY - Sum_of_X * Y_Mean) / &
          (Sum_of_X_squared - Sum_of_X * X_Mean)
  Y_Intercept = Y_Mean - Slope * X_Mean
  PRINT *
  PRINT *, "Equation of least-squares line is y =", &
            Slope, "x +", Y_Intercept

END PROGRAM Least_Squares_Line
