In this article, we will write a **C Program to calculate area of triangle using Heron’s formula.** According to Heron’s formula, the **area of the triangle is = sqrt(s * (s – a) * (s – b) * (s – c))**. Here *s* is the semi-perimeter of the triangle, whose value can be calculated using this formula s = (a+b+c)/2. The variables a, b and c are the sides of the triangle.

## C Program to calculate area of triangle using heron’s formula

#include <stdio.h>

#include <math.h>

int main() {

double a, b, c, s, area;

// Prompt user to enter the sides of the triangle

printf("Enter the lengths of the three sides of the triangle:\n");

printf("Side a: ");

scanf("%lf", &a);

printf("Side b: ");

scanf("%lf", &b);

printf("Side c: ");

scanf("%lf", &c);

// Calculate the semi-perimeter

s = (a + b + c) / 2.0;

// Calculate the area using Heron's formula

area = sqrt(s * (s - a) * (s - b) * (s - c));

// Check if the sides form a valid triangle

if (area > 0) {

// Print the area

printf("The area of the triangle is: %.2lf\n", area);

} else {

// Print an error message if entered sides do not form a valid triangle

printf("Entered values of sides do not form a valid triangle.\n");

}

return 0;

}

### Explanation of Program:

**Header files:**We have two header files included in this program,`<stdio.h>`

is used for`scanf`

and`printf`

, while`<math.h>`

is included so that we can use`sqrt()`

function.**Input**: The program prompts the user to enter the length of all three sides of triangle.**Semi-perimeter Calculation**: It calculated the value of semi-perimeter s using the formula s = (a+b+c)/2.**Area Calculation**: After getting the values of a, b, c from user and calculating the value of s, program calculates the area using formula area = sqrt(s * (s – a) * (s – b) * (s – c));**Validation**: In the last step, program checks whether the calculated area is positive or not. If it is positive then the area is printed, otherwise an error message is displayed that says the entered values of sides do not form a valid triangle.

### Output:

**Output 1: Valid Triangle**

Enter the lengths of the three sides of the triangle:

Side a: 3

Side b: 4

Side c: 5

The area of the triangle is: 6.00

**Output 2: Equilateral Triangle**

Enter the lengths of the three sides of the triangle:

Side a: 6

Side b: 6

Side c: 6

The area of the triangle is: 15.59

**Output 3: Invalid Triangle**

Enter the lengths of the three sides of the triangle:

Side a: 1

Side b: 2

Side c: 3

Entered values of sides do not form a valid triangle.

## Leave a Reply