Program to find line passing through 2 Points

Given two points P and Q in the coordinate plane, find the equation of the line passing through both the points.

This kind of conversion is very useful in many geometric algorithms like intersection of lines, finding the circumcenter of a triangle, finding the incenter of a triangle and many more…


Input : P(3, 2)
        Q(2, 6)
Output : 4x + 1y = 14

Input : P(0, 1)
        Q(2, 4)
Output : 3x + -2y = -2

Let the given two points be P(x1, y1) and Q(x2, y2). Now, we find the equation of line formed by these points.

Any line can be represented as,
ax + by = c
Let the two points satisfy the given line. So, we have,
ax1 + by1 = c
ax2 + by2 = c
We can set the following values so that all the equations hold true,

a = y2 - y1
b = x1 - x2
c = ax1 + by1

These can be derived by first getting the slope directly and then finding the intercept of the line. OR these can also be derived cleverly by a simple observation as under:

Derivation :

ax1 + by1 = c ...(i)
ax2 + by2 = c ...(ii)
Equating (i) and (ii),
ax1 + by1 = ax2 + by2
=> a(x1 - x2) = b(y2 - y1)
Thus, for equating LHS and RHS, we can simply have,
a = (y2 - y1)
b = (x1 - x2)
so that we have,
(y2 - y1)(x1 - x2) = (x1 - x2)(y2 - y1)
Putting these values in (i), we get,
c = ax1 + by1

Thus, we now have the values of a, b and c which means that we have the line in the coordinate plane.

// C++ Implementation to find the line passing
// through two points
#include <iostream>
using namespace std;
// This pair is used to store the X and Y
// coordinate of a point respectively
#define pdd pair<double, double>
// Function to find the line given two points
void lineFromPoints(pdd P, pdd Q)
    double a = Q.second - P.second;
    double b = P.first - Q.first;
    double c = a*(P.first) + b*(P.second);
     cout << "The line passing through points P and Q is: "
         << a << "x " << b << "y = " << c << endl;
     cout << "The line passing through points P and Q is: "
         << a << "x + " << b << "y = " << c << endl;
// Driver code
int main()
    pdd P = make_pair(3, 2);
    pdd Q = make_pair(2, 6);
    lineFromPoints(P, Q);
    return 0;


The line passing through points P and Q is: 4x + 1y = 14

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar