C++ Program to Find Area and Perimeter of an Equilateral Triangle
Introduction
Geometry is an essential part of mathematics and computer programming, often used to solve real-world problems. One such fundamental shape is the equilateral triangle, a triangle where all three sides are equal in length. This shape has unique properties that simplify the calculation of its area and perimeter. In this article, we will explore a C++ program that computes the area and perimeter of an equilateral triangle, explaining every step in detail to help you understand the logic behind the implementation.
Formulas
To calculate the area and perimeter of an equilateral triangle, we use the following formulas:
- Perimeter: The perimeter of an equilateral triangle is the sum of all its sides. Since all sides are equal:
Perimeter = 3 × Side
- Area: The area of an equilateral triangle is calculated using the formula:
Area = (√3 / 4) × Side²
, where√3
is approximately1.732
.
By using these formulas, we can efficiently calculate both the area and the perimeter using a single input: the side length of the triangle.
Code
Below is the C++ code to calculate the area and perimeter of an equilateral triangle:
#include <iostream> #include <cmath> using namespace std; int main() { // Input: Length of a side of the triangle double side; cout << "Enter the length of a side of the equilateral triangle: "; cin >> side; // Calculate the perimeter double perimeter = 3 * side; // Calculate the area double area = (sqrt(3) / 4) * pow(side, 2); // Output the results cout << "Perimeter of the equilateral triangle: " << perimeter << endl; cout << "Area of the equilateral triangle: " << area << endl; return 0; }
Output
Here's an example of how the program behaves during execution:
Enter the length of a side of the equilateral triangle: 6 Perimeter of the equilateral triangle: 18 Area of the equilateral triangle: 15.5885
The user enters the side length as 6
, and the program calculates and displays the perimeter as 18
and the area as approximately 15.5885
.
Explanation
Let's break down the code step by step:
-
Input: The program starts by asking the user to input the length of one side of the equilateral triangle. This value is stored in the variable
side
. -
Perimeter Calculation: Using the formula
Perimeter = 3 × Side
, the program multiplies the input value by 3 to find the perimeter. -
Area Calculation: The program computes the area using the formula
Area = (√3 / 4) × Side²
. It employs thesqrt
function from the<cmath>
library to calculate the square root of 3, and thepow
function to square the side length. -
Output: Finally, the program prints the calculated perimeter and area to the console using
cout
.
By combining straightforward user input, arithmetic operations, and output functions, this program demonstrates the simplicity and power of C++ for solving mathematical problems.