Heron’s Formula – Solution

The challenge for this month’s Exercise is to code Heron’s Formula. This geometric magic calculates the area of a triangle given the length of each of its three sides.

As a refresher, and to copy-paste from the original post, here is Heron’s Formula:

Heron's Formula

Semi-perimeter value s is obtained by using this formula:

Semi perimeter calculation

The difficult part of working with this formula is making up the lengths for the three sides, which isn’t officially part of the challenge. (Based on Chris W’s comment in the original post, I’ll address this issue in the future.) My solution is shown below, which gathers input from the user, obtains the semi-perimeter, then applies Heron’s Formula to generate the area for the given triangle.

2025_10-Exercise.c

#include <stdio.h>
#include <math.h>

int main()
{
    int x;
    float t[3],s,area;

    /* gather input for the three side lengths */
    for( x=0; x<3; x++ )
    {
        printf("Input the length of side %c: ",'A'+x);
        scanf("%f",&t[x]);
    }

    /* obtain the semi-perimeter */
    s = ( t[0] + t[1] + t[2] ) / 2.0;
    printf("Semi-perimeter is %.2f\n",s);

    /* apply Heron's Formula */
    area = sqrt( s * (s-t[0]) * (s-t[1]) * (s-t[2]) );
    printf("The triangle's area is %.2f units\n",area);

    return 0;
}

Variable x is the looping variable, which should always be an integer for precise iterations. The other variables, including array t[], are real numbers (float) to best calculate the triangle’s area.

I use the scanf() function in a loop to fetch the three side values from the user. No check is made to ensure that these values represent a valid triangle on a plain solid surface.

The semi-perimeter is calculated first:

s = ( t[0] + t[1] + t[2] ) / 2.0;

With the value of s determined, Heron’s Formula is applied by using this expression:

area = sqrt( s * (s-t[0]) * (s-t[1]) * (s-t[2]) );

You can compare this expression with the formula written above; sides a, b, and c are represented by array elements t[0], t[1], and t[2], respectively. A printf() statement outputs the result.

If you’re using Linux, remember that you must link in the math library for the sqrt() function to do its thing. The command line switch is -lm (little L).

Here’s a sample run with three valid triangle side lengths:

Input the length of side A: 3
Input the length of side B: 4
Input the length of side C: 5
Semi-perimeter is 6.00
The triangle's area is 6.00 units

Here is a sample run when invalid lengths are specified:

Input the length of side A: 10
Input the length of side B: 2
Input the length of side C: 40
Semi-perimeter is 26.00
The triangle's area is -nan units

As I wrote in the original post, the Heron’s Formula Wikipedia page features a gizmo that let’s you see the triangle formed with the lengths specified, which helps validate the input.

I hope that your solution met with success.

Leave a Reply