Linear Regression Method Using C++ with Output

This program is implementation of linear regression method as discussed in Linear Regression Method Algorithm and Linear Regression Method Pseudocode using C++.

C++ Program for Linear Regression


#include<iostream>


#define S 50

using namespace std;
int main()
{
 int n, i;
 float x[S], y[S], sumX=0, sumX2=0, sumY=0, sumXY=0, a, b;

 /* Input */
 cout<<"How many data points? ";
 cin>>n;

 cout<<"Enter data:"<< endl;

 for(i=1;i<=n;i++)
 {
  cout<<"x["<< i <<"] = ";
  cin>>x[i];
  cout<<"y["<< i <<"] = ";
  cin>>y[i];
 }

 /* Calculating Required Sum */
 for(i=1;i<=n;i++)
 {
  sumX = sumX + x[i];
  sumX2 = sumX2 + x[i]*x[i];
  sumY = sumY + y[i];
  sumXY = sumXY + x[i]*y[i];
 }
 /* Calculating a and b */
 b = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);
 a = (sumY - b*sumX)/n;

 /* Displaying value of a and b */
 cout<<"Calculated value of a is "<< a << "and b is "<< b << endl;
 cout<<"Equation of best fit is: y = "<< a <<" + "<< b<<"x";

 return(0);
}

Output

How many data points? 4
Enter data:
x[1] = 0
y[1] = -1
x[2] = 2
y[2] = 5
x[3] = 5
y[3] = 12
x[4] = 7
y[4] = 20
Calculated value of a is -1.13793and b is 2.89655
Equation of best fit is: y = -1.13793 + 2.89655x	

Recommended Readings

  1. Linear Regression Method Algorithm
  2. Linear Regression Method Pseudocode
  3. Linear Regression Method Using C Programming
  4. Linear Regression Method Using C++ with Output