
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
C program to compute linear regression
Problem
Write a program to implement linear regression algorithm.
User has to enter total number of values.
Solution
The solution to compute the linear regression in C programming language is as follows −
Linear regression finds the relationship between two variables by connecting a linear equation to the observed data. One variable is to be an explanatory variable, and the other is a dependent variable.
The logic with regards to linear regression is explained below −
for(i=0;i<n;i++){ printf("enter values of x and y"); scanf("%f%f",&x,&y); sumx=sumx+x; sumxsq=sumxsq+(x*x); sumy=sumy+y; sumxy=sumxy+(x*y); } d=n*sumxsq-sumx*sumx; m=(n*sumxy-sumx*sumy)/d; c=(sumy*sumxsq-sumx*sumxy)/d;
Finally, print m and c.
Example
Following is the C program to compute the linear regression −
#include<math.h> #include<stdio.h> main(){ int n,i; float x,y,m,c,d; float sumx=0,sumxsq=0,sumy=0,sumxy=0; printf("enter the number of values for n:"); scanf("%d",&n); for(i=0;i<n;i++){ printf("enter values of x and y"); scanf("%f%f",&x,&y); sumx=sumx+x; sumxsq=sumxsq+(x*x); sumy=sumy+y; sumxy=sumxy+(x*y); } d=n*sumxsq-sumx*sumx; m=(n*sumxy-sumx*sumy)/d; c=(sumy*sumxsq-sumx*sumxy)/d; printf("M=%f\tC=%f
",m,c); }
Output
When the above program is executed, it produces the following result −
enter the number of values for n:5 enter values of x and y1 5 enter values of x and y2 6 enter values of x and y2 4 enter values of x and y3 7 enter values of x and y1 1 M=2.000000 C=1.000000
- Related Articles
- C program to compute the polynomial regression algorithm
- Linear Regression
- Linear Regression using PyTorch?
- Linear Regression using Python?
- Linear regression with Matplotlib/Numpy
- Assumption of Linear Regression - Homoscedasticity
- Multiple Linear Regression in Machine Learning
- Difference Between Linear and Logistic Regression
- Simple Linear Regression in Machine Learning
- Locally Weighted Linear Regression in Python
- Assumptions of Linear Regression - Multivariate Normality
- C program to compute geometric progression
- How to plot statsmodels linear regression (OLS) cleanly in Matplotlib?
- How can Linear Regression be implemented using TensorFlow?
- Which Evaluation Metrics is Best for Linear Regression

Advertisements