w3resource

C++ Exercises: Print the area of a hexagon

C++ Basic: Exercise-57 with Solution

Hexagon Area Calculation

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

Visual Presentation:

C++ Exercises: Print the area of a hexagon

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; // Declaration of variables 'ar' and 's' to store area and side length respectively

    cout << "\n\n Print the area of a hexagon:\n"; // Displaying the purpose of the program
    cout << "---------------------------------\n";
    cout << " Input the side of the hexagon: "; // Prompting user to input side length
    cin >> s; // Taking input from user and storing it in variable 's'

    // Calculating the area of the hexagon using the formula: 6 * s^2 / (4 * tan(π/6))
    ar = (6 * (s * s)) / (4 * tan(M_PI / 6)); // M_PI represents the value of π

    cout << "The area of the hexagon is: " << ar << "\n"; // Displaying the calculated area

    return 0; // Returning 0 to indicate successful program execution
}

Sample Output:

 Print the area of a hexagon:                                          
---------------------------------                                     
 Input the side of the hexagon: 6                                    
The area of the hexagon is: 93.5307

Flowchart:

Flowchart: Print the area of a hexagon

C++ Code Editor:

Previous: Write a program in C++ to show the manipulation of a string.
Next: Write a program in C++ to print the area of a polygon.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/cpp-exercises/basic/cpp-basic-exercise-57.php