Saturday, January 21, 2012

Calculating the area of a polygon when the points are given in clockwise order

#include <iostream>


typedef struct
{
    double x, y;
}pp;


pp pnts[500];


int main()
{
    int n, i;
    while(1)
    {
        printf("How many points : (0 to terminate)\n");
        scanf("%d", &n);
        if(n==0)
            break;
        printf("Enter the points in clockwise order:\n");
        for(i=0;i<n;i++)
        {
            scanf("%lf %lf", &pnts[i].x, &pnts[i].y);
        }


        double area, x1, y1, x2, y2, cross, res;


        area = 0.0;


        for(i=1;i+1<n;i++)
        {
            x1 = pnts[i].x - pnts[0].x;
            y1 = pnts[i].y - pnts[0].y;
            x2 = pnts[i+1].x - pnts[0].x;
            y2 = pnts[i+1].y - pnts[0].y;
            cross = x1*y2 - x2*y1;
            area += cross;
        }


        res = abs(cross/2.0);
        /*int area = 0;
int N = lengthof(p);
//We will triangulate the polygon
//into triangles with points p[0],p[i],p[i+1]


for(int i = 1; i+1<N; i++){
    int x1 = p[i][0] - p[0][0];
    int y1 = p[i][1] - p[0][1];
    int x2 = p[i+1][0] - p[0][0];
    int y2 = p[i+1][1] - p[0][1];
    int cross = x1*y2 - x2*y1;
    area += cross;
}
return abs(cross/2.0);*/


        printf("Area of the polygon is %lf\n", res);
    }
    return 0;
}

No comments:

Post a Comment