C++ Program to Find Area and Perimeter of Scalene Triangle
Introduction
A scalene triangle is a triangle in which all three sides have different lengths, and consequently, all three angles are also distinct. Unlike equilateral or isosceles triangles, scalene triangles do not have any symmetrical properties, which makes their computation slightly more challenging.
This article demonstrates how to calculate the area and perimeter of a scalene triangle using a C++ program. We will discuss the necessary formulas, implement the logic in code, and analyze the output step by step.
Formulas
To compute the area and perimeter of a scalene triangle, we use the following formulas:
-
Perimeter: The perimeter is the sum of the lengths of all three sides:
Perimeter = side1 + side2 + side3
-
Area: To find the area, we use Heron's formula. First, calculate the semi-perimeter (
s
):s = (side1 + side2 + side3) / 2
. Then, use the formula:Area = sqrt(s * (s - side1) * (s - side2) * (s - side3))
.
Code
#include <iostream> #include <cmath> // For sqrt() function using namespace std; int main() { // Variables for the sides of the triangle double side1, side2, side3, semiPerimeter, area, perimeter; // Input the three sides of the triangle cout << "Enter the first side of the triangle: "; cin >> side1; cout << "Enter the second side of the triangle: "; cin >> side2; cout << "Enter the third side of the triangle: "; cin >> side3; // Calculate the perimeter perimeter = side1 + side2 + side3; // Calculate the semi-perimeter semiPerimeter = perimeter / 2; // Calculate the area using Heron's formula area = sqrt(semiPerimeter * (semiPerimeter - side1) * (semiPerimeter - side2) * (semiPerimeter - side3)); // Display the results cout << "Perimeter of the triangle: " << perimeter << endl; cout << "Area of the triangle: " << area << endl; return 0; }
Output
When the program is executed, it will prompt for the lengths of the three sides and compute the results. An example interaction is shown below:
Enter the first side of the triangle: 6 Enter the second side of the triangle: 8 Enter the third side of the triangle: 10 Perimeter of the triangle: 24 Area of the triangle: 24
Explanation
The program begins by asking for the lengths of the three sides of the scalene triangle. Using these inputs, it calculates the perimeter by summing up all three sides. The perimeter is then used to find the semi-perimeter:
s = (side1 + side2 + side3) / 2
.
With the semi-perimeter computed, the program uses Heron's formula to find the area. Heron's formula is especially useful for scalene triangles since it does not require the height to be calculated separately.
The formula:
Area = sqrt(s * (s - side1) * (s - side2) * (s - side3))
ensures that the computation is accurate regardless of the side lengths.