w3resource

C++ Exercises: Print the area of a polygon


Polygon Area Calculation

Write a C++ program to print the area of a polygon.

Visual Presentation:

C++ Exercises: Print the area of a polygon

Sample Solution:

C++ Code :

#include <iostream> // Including input-output stream header file
#include <math.h>   // Including math functions header file

using namespace std; // Using the standard namespace

int main() { // Start of the main function

    float ar, s, n; // Declaration of variables 'ar', 's', and 'n' to store area, side length, and number of sides respectively

    cout << "\n\n Print the area of a polygon:\n"; // Displaying the purpose of the program
	cout << "---------------------------------\n";
	
	cout << " Input the number of sides of the polygon: "; // Prompting user to input the number of sides
	cin >> n; // Taking input from user and storing it in variable 'n'
	
	cout << " Input the length of each side of the polygon: "; // Prompting user to input the side length
	cin >> s; // Taking input from user and storing it in variable 's'
	
	// Calculating the area of the polygon using the formula: n * s^2 / (4 * tan(π / n))
	ar = (n * (s * s)) / (4.0 * tan((M_PI / n))); // M_PI represents the value of π
	
	cout << " The area of the polygon is: " << ar << "\n"; // Displaying the calculated area
	
	return 0; // Returning 0 to indicate successful program execution
}

Sample Output:

Print the area of a polygon:                                          
---------------------------------                                      
 Input the number of sides of the polygon: 7                           
 Input the length of each side of the polygon: 6                       
 The area of the ploygon is: 130.821
 

Flowchart:

Flowchart: Print the area of a polygon

For more Practice: Solve these Related Problems:

  • Write a C++ program to calculate the area of a regular polygon using the apothem and perimeter, given the number of sides and side length.
  • Write a C++ program that computes the area of an irregular polygon using the shoelace formula and displays intermediate calculations.
  • Write a C++ program to calculate the area of a polygon by decomposing it into triangles and summing their areas.
  • Write a C++ program that takes the number of sides and side lengths of a polygon, then computes and prints its area with error handling for invalid polygons.

Go to:


PREV : Hexagon Area Calculation.
NEXT : Earth Surface Distance.

C++ Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.