Program to calculate the area of triangle using Heron’s formula
Write a program to calculate the area of triangle using formula, Area = √s(s-a) (s-b) (s-c)- heron’s formula.
Code
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, s, area;
printf("Enter 1st side:");
scanf("%f", &a);
printf("Enter 2nd side:");
scanf("%f", &b);
printf("Enter 3rd side:");
scanf("%f", &c);
s= (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Semiperimeter: %f\n",s);
printf("Area: %f",area);
return 0;
}
Description
Calculating the area of a triangle is a common task in many programming applications. In this blog post, we will discuss how to write a program in C language to calculate the area of a triangle using the formula Area = √s(s-a) (s-b) (s-c), where s is the semi-perimeter of the triangle and a, b, and c are the lengths of the three sides.
Before we dive into the program, let’s review the formula for the area of a triangle. The formula involves the calculation of the semi-perimeter s, which is half the sum of the three sides: s = (a + b + c) / 2. The area of the triangle can then be calculated using the formula:
Area = √s(s-a) (s-b) (s-c)
Now that we understand the formula, let’s understand the code mentioned above for the same.
In this program, we first include the necessary header files stdio.h and math.h. Then we declare the variables for the three sides of the triangle, the semi-perimeter, and the area. We prompt the user to enter the lengths of the three sides of the triangle using the printf and scanf functions. We then calculate the semi-perimeter and the area of the triangle using the formula. Finally, we print the result using the printf function.
Let’s test the program with an example. Suppose we have a triangle with sides of length 3, 4, and 5. We can run the program and input these values:
Output
Enter 1st side:3
Enter 2nd side:4
Enter 3rd side:5
Semiperimeter: 6.000000
Area: 6.000000
This result matches the well-known fact that a triangle with sides of length 3, 4, and 5 has an area of 6.
In conclusion, we have seen how to write a program in C language to calculate the area of a triangle using the formula Area = √s(s-a) (s-b) (s-c). This program can be used in many applications where the area of a triangle needs to be calculated.
You can watch this video as well for detailed Explanation.