Skip to content

Commit 9daa77c

Browse files
Create areaOfConvexPolygon.cpp
1 parent 1a2eab9 commit 9daa77c

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
A convex polygon is a set of n vertices that are joined by n edges, such that no two edges intersect and all angles are less than 180 degrees. We can represent a polygon by listing all the vertices, starting at one vertex and following the edges until that vertex is reached again. Thus, element 0 in the array represents the first vertex. The first vertex is connected to the second vertex (element 1), the second vertex is connected to the third vertex (element 2) and so on. The last element represents the last vertex, which is connected to the first vertex.
3+
Given the vertices of a polygon, where the x-coordinate of vertex i is element i of int[] x and its y-coordinate is element i of int[] y, return its exact area.
4+
Input Format
5+
Integer N
6+
Two arrays x and y of size N
7+
Output Format
8+
Area of polygon
9+
Notes
10+
Get the integer part of the area. (It can be long)
11+
So get your answer in double, and typecast it into long.
12+
Constraints
13+
x and y will have the same number of elements.
14+
x will have between 3 and 50 elements inclusive.
15+
y will have between 3 and 50 elements inclusive.
16+
each element in x will be between -10000 and 10000 inclusive.
17+
each element in y will be between -10000 and 10000 inclusive.
18+
the represented polygon will NOT intersect itself.
19+
the represented polygon will NOT have any angles equal to or greater than 180 degrees.
20+
Sample Input
21+
3
22+
0 0 1
23+
0 1 0
24+
Sample Output
25+
0
26+
(Exact area was 0.5 . In Integer It is 0)
27+
*/
28+
29+
#include<bits/stdc++.h>
30+
#define endl '\n'
31+
using namespace std;
32+
class point
33+
{
34+
public:
35+
double x, y;
36+
};
37+
class polygon
38+
{
39+
public:
40+
point*points;
41+
polygon(int number_of_points)
42+
{
43+
points=new point [number_of_points];
44+
}
45+
46+
};
47+
double area(polygon p, int n)
48+
{
49+
double total_area=0;
50+
for(int i=1; i<n-1; i++)
51+
{
52+
double x1=p.points[i].x-p.points[0].x;
53+
double y1=p.points[i].y-p.points[0].y;
54+
double x2=p.points[i+1].x-p.points[0].x;
55+
double y2=p.points[i+1].y-p.points[0].y;
56+
57+
58+
double cross_product=x1*y2-y1*x2;
59+
total_area+=cross_product;
60+
}
61+
return abs(total_area/2);
62+
}
63+
int main()
64+
{
65+
int n;
66+
cin>>n;
67+
polygon p(n);
68+
for(int i=0; i<n; i++)
69+
{
70+
cin>>p.points[i].x;
71+
}
72+
for(int i=0; i<n; i++)
73+
{
74+
cin>>p.points[i].y;
75+
}
76+
//area
77+
cout<<(int)area(p, n)<<endl;
78+
}

0 commit comments

Comments
 (0)