How to check if a point is inside a rectangle in C++

1 Answer

0 votes
#include <iostream>

struct Point {
    double x, y;
};

struct Rectangle {
    Point topLeft;     // Top-left corner of the rectangle
    Point bottomRight; // Bottom-right corner of the rectangle
};

bool isPointInsideRectangle(const Point& p, const Rectangle& rect) {
    return (p.x >= rect.topLeft.x && p.x <= rect.bottomRight.x &&
            p.y >= rect.topLeft.y && p.y <= rect.bottomRight.y);
}

int main() {
    Rectangle rect = {{0.0, 0.0}, {7.0, 7.0}}; // Rectangle from (0,0) to (7,7)
    Point p = {3.0, 2.0};                      // Point to check

    if (isPointInsideRectangle(p, rect)) {
        std::cout << "The point is inside the rectangle.\n";
    } else {
        std::cout << "The point is outside the rectangle.\n";
    }
}



/*
run:

The point is inside the rectangle.

*/

 



answered Jun 21, 2025 by avibootz

Related questions

...