Write a C program to implement the linear regression algorithm.

Algorithm:

Step 1.  Read n
Step 2.  sumx = 0
Step 3.  sumxsq = 0
Step 4.  sumy = 0
Step 5.  sumxy = 0
Step 6.  for i = 1 to n do
Step 7.  Read x, y
Step 8.  sumx = sumx + x
Step 9.  sumxsq = Sumxsq + x2
Step 10. sumy = Sumy + y
Step 11. sumxy = sumxy + x * y end for
Step 12. denom = n * sumxsq – sumx * sumx
Step 13. a0 = (sumy * sumxsq – sumx * sumxy) / denom
Step 14. a1 = (n * sumxy - sumx * sumy) / denonm
Step 15. Write a1, a0
Step 16. Stop

Flowchart:

Program:

#include<stdio.h>
#include<math.h>
main()
{
 int n,I;
 float sumx, sumxsq, sumy, sumxy, x, y, a0, a1, denom;
 printf(“enter the n value”);
 scanf(“%d”, &n);
 sumx = 0;
 sumsq = 0;
 sumy = 0;
 sumxy = 0;
 for(i = 0; i < n; i++)
 {
  scanf(“%f %f”, &x, &y);
  sumx += x;
  sumsq += pow(x, 2);
  sumy += y;
  sumxy += x * y;
 }
 denom = n * sumxsq – pow(sumx, 2);
 a0 = (sumy * sumxsq – sumx * sumxy) / denom;
 a1 = (n * sumxy – sumx * sumy) / denom;
 printf(“y = %fx + %f”,a1, a0);
}

Input & Output:

enter the n value 7
1 2
2 5
4 7
5 10
6 12
8 15
9 19
Y = 1.980769x + 0.096154