C++ Program to Find Area and Perimeter of Isosceles Triangle

C++ Program to Find Area and Perimeter of Isosceles Triangle

C++ Program to Find Area and Perimeter of Isosceles Triangle


Introduction

An isosceles triangle is a type of triangle that has at least two sides of equal length. These equal sides are called the legs, and the third side is referred to as the base. Isosceles triangles have unique properties, such as equal angles opposite the equal sides, making them fascinating in both mathematics and programming.

In this article, we will learn how to calculate the area and perimeter of an isosceles triangle using a simple C++ program. Understanding the underlying formulas and concepts will make it easier to implement the code.


Formulas

To calculate the area and perimeter of an isosceles triangle, we use the following formulas:

  • Perimeter: The perimeter of a triangle is the sum of its three sides. For an isosceles triangle: Perimeter = 2 * leg + base
  • Area: The area of an isosceles triangle is calculated using the formula: Area = (base * height) / 2
  • To find the height, which is perpendicular from the base to the opposite vertex, we use the Pythagorean theorem: height = sqrt(leg² - (base/2)²)

Code

#include <iostream>
#include <cmath> // For sqrt() function

using namespace std;

int main() {
    // Variables for dimensions
    double leg, base, height, area, perimeter;

    // Input for leg and base
    cout << "Enter the length of the equal sides (legs): ";
    cin >> leg;
    cout << "Enter the length of the base: ";
    cin >> base;

    // Calculate height using Pythagorean theorem
    height = sqrt((leg * leg) - ((base / 2) * (base / 2)));

    // Calculate area
    area = (base * height) / 2;

    // Calculate perimeter
    perimeter = (2 * leg) + base;

    // Output the results
    cout << "Height of the triangle: " << height << endl;
    cout << "Area of the triangle: " << area << endl;
    cout << "Perimeter of the triangle: " << perimeter << endl;

    return 0;
}
    

Output

When you run the above program, it will ask for the lengths of the legs and base. Below is an example output:

Enter the length of the equal sides (legs): 5
Enter the length of the base: 6
Height of the triangle: 4
Area of the triangle: 12
Perimeter of the triangle: 16
    

Explanation

The program first takes input for the lengths of the equal sides (legs) and the base. It calculates the height using the Pythagorean theorem: height = sqrt(leg² - (base/2)²). This step ensures that the program correctly calculates the height even for larger or smaller triangles.

Once the height is computed, it is used to find the area with the formula: Area = (base * height) / 2. Finally, the program calculates the perimeter by summing up the lengths of all three sides.

The use of cmath ensures accurate calculation of square roots, and the program gracefully handles user inputs to deliver precise results for different triangle dimensions.