Hacker Challenge: Locating the Point P

Let's write a program to determine whether a point P lies within or outside a square.

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 axis-parallel.This means all sides of the square are either parallel or perpendicular to the x and y-axis.

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

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

  2. Whether the y-axis of the P lies within the y-axis of the two points along the y-axis (for instance, P1 and P4, or P2 and P3).

If both the conditions are true, and the x and y-axis of the point P lie within the x and y-axis 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;
}
Point p lies inside rectangle or not

Instruction: Write your code in the provided playground above. Use the example input, given in the question as a reference.