
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a line passes through the origin in C++
In this article, we have a line and its coordinates are given. Our task is to check if this line passes through the origin or not.
The basic two-point form of a straight line is given by:
$$ \frac{y - y_1}{y_2 - y_1} = \frac{x - x_1}{x_2 - x_1} + c $$
For the above line to pass through the origin, put x = 0, y = 0, and c = 0. The formula for a straight line to pass through the origin can be given by:
$$ y_1(x_2 - x_1) = x_1(y_2 - y_1) $$
Here are some example scenarios to check if the given line can pass through the origin:
Scenario 1
Input: (x1, y1) = (2, 3), (x2, y2) = (3, 2) Output: Does Not Pass Through Origin Explanation Equation of line passing through origin: x1 ?y2-y1? = y1 ?x2-x1? 2 (2-3) = 3 (3-2) -2 != 3 => This line does not pass through the origin
Scenario 2
Input: (x1, y1) = (2,4), (x2, y2) = (4,8) Output: Passes through origin Explanation Equation of line passing through origin: x1 ?y2-y1? = y1 ?x2-x1? 2 (8-4) = 4 (4-2 ) 8 = 8 => This line passes through the origin
How to check if a line passes through the origin in C++?
If you are given two points (x1, y1)
and (x2, y2)
, and you want to check whether the line joining these two points passes through the origin (0, 0)
, you can use the concept of the slope.
The slope of the line from origin to point (x1, y1)
is y1 / x1
, and the slope of the line from origin to (x2, y2)
is y2 / x2
. If both slopes are equal, then the line passes through the origin.
We can avoid division (and handle division by zero) by cross-multiplying:
y1 * (x2 - x1) == x1 * (y2 - y1)
If the above equation holds true, then the line formed by points (x1, y1)
and (x2, y2)
passes through the origin.
C++ Code to Check if Line Passes Through Origin
Here is an example code of checking the coordinate points, (2, 4) and (4, 8), if they pass through the origin (0,0) or not using the above formula:
#include<iostream> using namespace std; bool checkPassOrigin(int x1, int y1, int x2, int y2) { return (x1 * (y2 - y1) == y1 * (x2 - x1)); //Formula } int main() { if (checkPassOrigin(2, 4, 4, 8) == true) cout << "Passes Through Origin"; else cout << "Not Passing Through Origin"; return 0; }
The output of the above code is as follows:
Passes Through Origin