## C++ Program for Hit Testing. Determine whether a point is inside a rectangle.

P, Q, R and S are vertices of a rectangle in a clockwise cyclic order. The axes are cartesian where x is positive to the right, y is positive upwards. The coordinates of P are: (-6.1f, -4.3f), Q: (-6.1f, +4.3f), R: (+6.1f, +4.3f) and S: (+6.1f, -4.3f). Ask the user to enter the coordinates of a point of his choice. Write code to determine whether that point lies inside the rectangle or not. You have to model the problem into a C program. Test this program by entering x as 0.0 and y as 0.0. If your code is correct, the output would be: "Yes, inside!".

#include <iostream> using namespace std; int main() { // points are cyclic float PX = -6.1f, PY = -4.3f; float QX = -6.1f, QY = +4.3f; float RX = +6.1f, RY = +4.3f; float SX = +6.1f, SY = -4.3f; float x, y; cout << "Enter x-coord: "; cin >> x; cout << "Enter y-coord: "; cin >> y; /* Q___________________R | | | | | | | | P___________________S */ if( (y < QY) && (y > PY) && (x < RX) && (x > QX) ) { cout << "Yes, Inside!" << endl; } else { cout << "Outside" << endl; } return 0; }

## My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.

This Blog Post/Article "Determine whether a point is inside a rectangle" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Updated on 2019-08-18.