Linear Regression Method Using C Programming

In our previous article Linear Regression Method Algorithm and Linear Regression Method Pseudocode we developed algorithm and pseudocode for fitting curve y = a + bx (linear regression). In this article we are going to implement this method using C programming language. We have also provided output for this method.

C Program for Linear Regression (Fitting y = a+bx)


#include<stdio.h>
#include<conio.h>

#define S 50

int main()
{
 int n, i;
 float x[S], y[S], sumX=0, sumX2=0, sumY=0, sumXY=0, a, b;
 clrscr();
 /* Input */
 printf("How many data points?\n");
 scanf("%d", &n);
 printf("Enter data:\n");
 for(i=1;i<=n;i++)
 {
  printf("x[%d]=",i);
  scanf("%f", &x[i]);
  printf("y[%d]=",i);
  scanf("%f", &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 */
 printf("Values are: a=%0.2f and b = %0.2f",a,b);
 printf("\nEquation of best fit is: y = %0.2f + %0.2fx",a,b);
 getch();
 return(0);
}

Output: Linear Regression Using C Programming Language

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↲
Values are: a=-1.14 and b=2.90
Equation of best fit is: y = -1.14 + 2.90x

Note: ↲ indicates ENTER is pressed.

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