C++ Program to implement Slicker Algorithm that avoids Triangulation to find Area of a Polygon


Here is a C++ program to find the area of polygon using slicker algorithm that avoids Triangulation to find area of a polygon.

It assumes the usual mathematical convention that positive y points upwards. In computer systems where positive y is downward, the easiest thing to do is to list the vertices counter-clockwise using the “positive y down” coordinates. Two effects then canceled out to produce a positive area.

Functions and pseudocode

Algorithm

Begin
   function Area() is used to calculate area of a polygon take the polygon p as argument.
   for i = 0 to p.n-1
      initialize j = (i + 1) % p.n;
      calculate t =t+((p.p[i].b * p.p[j].b) - (p.p[j].a * p.p[i].b.))
      return t/2
End

Example Code

#include <iostream>
using namespace std;

const int MAX = 200;
class P// to declare variables {
   private:
      public:
         double a, b;
};

class Polygon {
   private:
      public:
         P p[MAX];
         int n;

         Polygon()//take the coordinates of each point of polygon {
            for (int i = 0; i < MAX; i++)
               P p[i];
         }
};

double Area(Polygon p)//area calculation {
   double t = 0;
   for (int i = 0; i < p.n; i++) {
      int j = (i + 1) % p.n;
      t += (p.p[i].b * p.p[j].b) - (p.p[j].a * p.p[i].b);
   }
   return t / 2;
}

int main(int argc, char **argv) {
   Polygon p;

   cout << "Enter the number of points in Polygon: ";
   cin >>p.n;
   cout << "Enter the coordinates of each point: ";
   for (int i = 0; i < p.n; i++) {
      cin >>p.p[i].a;
      cin >>p.p[i].b;
   }

   double a = Area(p);
   if (a >0)//if area>0
      cout << "The Area of Polygon with " << p.n
      << " points using Slicker Algorithm is : " << a;
   else
      cout << "The Area of Polygon with " << p.n
      << " points using Slicker Algorithm is : " << (a * -1);
}

Output

Enter the number of points in Polygon: 6
Enter the coordinates of each point:
1 1
2 2
3 3
4 4
5 5
6 7
The Area of Polygon with 6 points using Slicker Algorithm is : 2.5

Updated on: 30-Jul-2019

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements