Polygon in a Two Dimensional Space (Id-1535)
Bonus Practice Sheet Winter 2018 [17-Mar-2018 to 7-Apr-2018]
Design a class polygon to represent a polygon in a two dimensional space. Provide member functions to get the details of the polygon and compute area. Area of a polygon with ‘n’ vertices is given by the following formula:
Here the vertices are numbered from 1 to n either clockwise or anticlockwise. The sign of the value changes when numbering is done in the other way. So absolute value is considered.
Derive two classes: triangle and quadrilateral, from the class polygon. Overload the operator [] to get the ‘i-th’ point of the polygon if ‘i’ is less than or equal to the number of vertices ‘n’ and raise an user defined exception outofrange when ‘i’ is greater than ‘n’. Catch the exception in main and print ‘outofrange’.
Input Format
Next six entries are Vertices of a triangle
value of X- coordinate of point1
value of Y- coordinate of point1
….
value of X- coordinate of point6
value of Y- coordinate of point6
Next eight entries are Vertices of a triangle
value of X- coordinate of point1
value of Y- coordinate of point1
….
value of X- coordinate of point8
value of Y- coordinate of point8
index of the vertex of the polygon, whose coordinate has to be printed.
Output Format
Area of triangle
Area of quadrilateral
Value of X- coordinate and Y- coordinate of point-n separated by tab or print Out of range if index is not in range
Please Comment Working if the code worked to you
If you have other working codes please comment the codes enclosing with <pre> and </pre> 🙂
Example: <pre> Your Code </pre>
C++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | point :: point(){} void point :: get() { cin>>x>>y; } ostream& operator << (ostream& out,point p) { out<<p.x<<"\t"<<p.y; return(out); } void outofrange :: what() { cout<<"Out of range"; } polygon :: polygon(int m) { num_Of_Ver=m; vertices=new point[m]; } void polygon :: get() { for(int i=0;i < num_Of_Ver;i++) vertices[i].get(); } point& polygon :: operator [](int idx) { if(idx < num_Of_Ver) return(vertices[idx]); else { outofrange o; throw(o); } } double polygon :: area() { double ar=0; for(int i=0;i < num_Of_Ver-1;i++) ar+=vertices[i].x*vertices[i+1].y-vertices[i+1].x*vertices[i].y; ar+=vertices[num_Of_Ver-1].x*vertices[0].y-vertices[num_Of_Ver-1].y*vertices[0].x; if(ar/2<0) return(-ar/2); return(ar/2); } polygon :: ~polygon(){} |