C++ program to check if two rectangles overlap or not














































C++ program to check if two rectangles overlap or not



Description:

We know that a rectangle can be represented using two coordinates, the top left corner, and the bottom right corner. Suppose there are two rectangles, we have to check whether these two overlap or not. There are four coordinate points (l1, r1) and (l2, r2).

  • l1 is the top-left corner of first rectangle
  • r1 is the bottom-right corner of the first rectangle
  • l2 is the top-left corner of second rectangle
  • r2 is the bottom-right corner of the second rectangle

We have assumed that the rectangles are parallel to the coordinate axes. 

To solve this, we have to check a few conditions.

  • One rectangle is above the top edge of another rectangle
  • One rectangle is on the left side of the left edge of another rectangle.


C++ program to find if two rectangles overlap or not

#include<bits/stdc++.h>
using namespace std; struct point{ int x,y; }; int main() { point l1; //upper left co-ordinate of first rectangle point r1; //bottom right co-ordinate of first rectangle point l2; //upper left co-ordinate of second rectangle point r2; //bottom right co-ordinate of second rectangle cout<<"Enter upper left co-ordinate of first rectangle\n"; cin>>l1.x; cin>>l1.y; cout<<"Enter bottom right co-ordinate of first rectangle\n"; cin>>r1.x; cin>>r1.y; cout<<"Enter upper left co-ordinate of second rectangle\n"; cin>>l2.x; cin>>l2.y; cout<<"Enter bottom right co-ordinate of second rectangle\n"; cin>>r2.x; cin>>r2.y; if (l1.x > r2.x || l2.x > r1.x) cout<<"Rectangles are not overlapping\n"; else if (l1.y < r2.y || l2.y < r1.y) cout<<"Rectangles are not overlapping\n"; else cout<<"Rectangles are overlapping\n"; return 0; }

Output :

Enter upper left co-ordinate of first rectangle
0 10 Enter bottom right co-ordinate of first rectangle
10 0 Enter upper left co-ordinate of second rectangle
5 5 Enter bottom right co-ordinate of second rectangle
15 0

Rectangles are overlapping

Comments