c > math > equation of a straight line

Equation of a Straight Line

Any straight line can be written in the standard form: $$y=mx+c$$

The gradient, $m$ is given by the formula: $$m=\frac{y_2-y_1}{x_2-x_1}$$

The y-intercept, $c$ can be found by substituting the gradient and any of the points (in this case we use $(x_1,y_1)$) into the standard form of the line equation: $$y_1=mx_1+c$$ $$\therefore c=y_1-mx_1$$

The following code snippet shows how we can replicate this in C:

#include <stdio.h>

int main(){
    // storing the points
    double x1=-2.5,x2=0,y1=0,y2=5;
    printf("Using the points (%g,%g) and (%g,%g)\n",x1,y1,x2,y2);
    // calculating gradient
    double gradient = (y2-y1)/(x2-x1);
    printf("The gradient of the line is %g\n",gradient);

    //calculating the y-intercept
    double y_intercept = y1-gradient*x1;
    printf("The y intercept is %g\n",y_intercept);

    // displaying the final equation of the straight line
    printf("Therefore the equation of the line is:\ny=%gx+%g",gradient,y_intercept);
    return 0;

↗ Open 📋 Copy c/math/finding_the_equation_of_a_line_given_two_points.c