Hacker Challenge: Locating the Point P
Let's write a program to determine whether a point P lies within or outside a square.
We'll cover the following
In this lesson, weâ€™ll write a program to determine whether some point P lies within or outside a region.
So letâ€™s begin!
Locating the point P
Problem statement
Write a program that takes four coordinates with the x and y coordinates as input from a user (p1x
, p1y
), (p2x
, p2y
), (p3x
, p3y
), (p4x
, p4y
) and a point P (px
, py
) in a counterclockwise fashion. Our program should find out whether point P lies inside the square or not.
We are assuming that the square is
axisparallel. This means all sides of the square are either parallel or perpendicular to the x and yaxis.
Sample Input
P1 0 0
P2 2 0
P3 2 2
P4 0 2
P 1 1
Sample output
P lies inside the square.
Take a moment and think of the solution.
We have four points and a point P. Should we calculate the distance of all sides? But that canâ€™t be helpful.
To know whether a point lies within a region or not, we can simply determine

Whether the xaxis of the point P is within the xaxis of the two points along the xaxis (for instance, P1 and P2, or P4 and P3).

Whether the yaxis of the P lies within the yaxis of the two points along the yaxis (for instance, P1 and P4, or P2 and P3).
If both the conditions are true, and the x and yaxis of the point P lie within the x and yaxis of the square, then the point P is within the region. If not, then the point lies outside the region. If neither, the point lies on the region line.
Letâ€™s draw points P1, P2, P3, P4, and P (counterclockwise) on the plane:
Letâ€™s write down our program for the above problem:
Your Implementation
Write your implementation here.
#include<iostream> using namespace std; int main() { char choice; int p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y,px,py; cout << "The x and y coordinates of the 4 points: " << endl; cin >> p1x >> p1y; cin >> p2x >> p2y; cin >> p3x >> p3y; cin >> p4x >> p4y; cout << "The x and y coordinates of the point p: " << endl; cin >> px >> py; // Write your code here... return 0; }
Instruction: Write your code in the provided playground above. Use the example input, given in the question as a reference.