# Check If It Is a Straight Line in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of data-points consisting of (x, y) coordinates, we have to check whether the data-points are forming straight line or not. So if the points are like [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)], then they are forming straight line.

To solve this, we will take the differences between each consecutive datapoints, and find the slope. For the first one find the slope. For all other points check whether the slope is same or not. if they are same, then simply return true, otherwise false

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int gcd(int a, int b){
return !b?a:gcd(b,a%b);
}
bool checkStraightLine(vector<vector<int>>& c) {
bool ans =true;
bool samex = true;
bool samey = true;
int a = c-c;
int b = c-c;
int cc = gcd(a,b);
a/=cc;
b/=cc;
for(int i =1;i<c.size();i++){
int x = c[i]-c[i-1];
int y = c[i]-c[i-1];
int z = gcd(x,y);
x/=z;
y/=z;
ans =ans &&(x == a )&& (y == b );
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> c = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}};
cout << ob.checkStraightLine(c);
}

## Input

[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]

## Output

1
(1 indicates true)