C Program to Find Area and Perimeter of a Scalene Triangle
Introduction
A scalene triangle is a type of triangle where all three sides are of different lengths. Unlike equilateral or isosceles triangles, it has no equal sides or angles. Finding the area and perimeter of a scalene triangle requires knowledge of its three sides and sometimes the height or semi-perimeter for area calculations.
In this guide, we will write a C program to calculate both the area and perimeter of a scalene triangle. We will use Heron's formula for the area calculation and the sum of the sides for the perimeter.
Formulas
1. Perimeter
The perimeter of a triangle is the sum of its three sides:
Perimeter = a + b + c
2. Area
To find the area of a scalene triangle, we use Heron's formula. This involves calculating the semi-perimeter (s) first:
- Semi-perimeter (s): s = (a + b + c) / 2
- Area: Area = √[s(s - a)(s - b)(s - c)]
Here:
- a, b, c are the lengths of the three sides.
- s is the semi-perimeter.
Code
Below is the C program to calculate the area and perimeter of a scalene triangle:
#include <stdio.h> #include <math.h> int main() { double a, b, c, s, area, perimeter; // Input the sides of the triangle printf("Enter the three sides of the scalene triangle:\n"); scanf("%lf %lf %lf", &a, &b, &c); // Calculate the perimeter perimeter = a + b + c; // Calculate the semi-perimeter s = perimeter / 2; // Calculate the area using Heron's formula area = sqrt(s * (s - a) * (s - b) * (s - c)); // Display the results printf("Perimeter of the scalene triangle: %.2lf\n", perimeter); printf("Area of the scalene triangle: %.2lf\n", area); return 0; }
Output
When the above program is executed, it prompts the user to input the three sides of the scalene triangle and displays the calculated area and perimeter. Below is a sample run:
Enter the three sides of the scalene triangle: 5 6 7 Perimeter of the scalene triangle: 18.00 Area of the scalene triangle: 14.70
Explanation
The program starts by taking the lengths of the three sides of the scalene triangle as input from the user. These inputs are stored in variables a, b, and c. It then calculates the perimeter using the formula:
Perimeter = a + b + c
Next, it computes the semi-perimeter, s, using:
s = (a + b + c) / 2
To find the area, the program applies Heron's formula:
Area = √[s(s - a)(s - b)(s - c)]
The math.h library function sqrt() is used to compute the square root. Finally, the results are displayed to the user with two decimal places for clarity.
This program ensures accurate calculations and can handle any valid inputs for a scalene triangle. If the inputs do not form a valid triangle, the area calculation may result in a math error, which can be avoided by adding an additional validation step (not included in the current version).