×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to find the area of polygon of several sides using class

Learn, how can we find the area of polygon of several sides using the class and object approach?
Submitted by Shubh Pachori, on September 04, 2022

Problem statement

Given the sides and length of the sides, find the area of polygon of several sides using the class and object approach in C++.

Example:

Input:  
Enter Sides: 7
Enter Length of sides: 6

Output: 
Area of polygon is 130.821

C++ code to find the area of polygon of several sides using the class and object approach

#include <math.h>
#include <iostream>
using namespace std;

// create a class
class Polygon {
  // private data members
 private:
  float sides, length, area;

  // public member functions
 public:
  // putSides() function to insert number of
  // sides and length of sides
  void putSides() {
    cout << "Enter Sides: ";
    cin >> sides;

    cout << "Enter Length of sides: ";
    cin >> length;
  }

  // getArea() function to calculate 
  // the area of the polygon
  double getArea() {
    // calculating area of the polygon
    area = (sides * (length * length)) / (4.0 * tan((M_PI / sides)));

    // returning area
    return area;
  }
};

int main() {
  // create object
  Polygon P;

  // float type variable to store area
  float area;

  // calling putSides() function to insert number
  // sides and length of the side
  P.putSides();

  // calling getArea() function to 
  // calculate area of the polygon
  area = P.getArea();

  cout << "Area of polygon is " << area << endl;

  return 0;
}

Output

Enter Sides: 8
Enter Length of sides: 8
Area of polygon is 309.019

Explanation

In the above code, we have created a class Polygon, three float type data members sides, length and area to store the number of sides, length of sides and area of the polygon, and public member functions putSides() and getArea() to store sides and their lengths and to calculate the area of the polygon.

In the main() function, we are creating an object P of class Polygon, reading the inputted values by the user using putSides() function, and finally calling the getArea() member function to calculate the area of the polygon. The getArea() function contains the logic to calculate the area of the polygon and printing the result.

C++ Class and Object Programs (Set 2) »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.