Calculate Area of Irregular Polygon with C++

Area under curve of irregular polygon

Use C++ to calculate area using shoelace formula

24 Jul 2022

mathhomeworkc++

Introduction

This is an implementation of shoelace algorithm in C++

Code

/*By Kougmeng 19/07/2022*/
#include <iostream>

int main(void)
{
    float sum = 0.0f;
    const int number_of_polygon = 7;
    //List the coordinates in counter - clockwise
    //and add the first point to the array to make a complete loop
    float coordinates[number_of_polygon+1][2] = { {1.0f, 2.0f}, {0.0f, 0.0f},{-3.0f, -1.0f},
        {3.0f, -2.0f}, {4.0f,2.0f}, {0.0f,3.0f}, {-2.0f,0.0f}, {1.0f,2.0f} };

    for (int i = 0; i < number_of_polygon; i++)
    {
        sum += coordinates[i][0] * coordinates[i + 1][1] - coordinates[i + 1][0] * coordinates[i][1];
    }
    float area = sum / 2;

    std::cout << "The area of the shape is: " << area << std::endl;
    std::cin.get();
}

Usage

To calculate area you need to change the variable number_of_polygon to the number of polygon your shape has. And change the coordinates array to the coordinate of each vertices of your shape. You need to list it in counter-clockwise position, and don't forget to add the first vertex to the back of the array to create a loop.

Example and Output