Programming Example 3: Heron's Formula for Computing Triangle Area

Problem Statement

Given a triangle with side lengths a, b and c, its area can be computed using the Heron's formula:

where s is the half of the perimeter length:

Write a program to read in the coefficients a, b and c, and compute the area of the triangle. However, not any three numbers can make a triangle. There are two conditions. First, all side lengths must be positive:

and second the sum of any two side lengths must be greater than the third side length:

In the program, these two conditions must be checked before computing the triangle area; otherwise, square root computation will be in trouble.


! ------------------------------------------------------
! Compute the area of a triangle using Heron's formula
! ------------------------------------------------------

PROGRAM  HeronFormula

   REAL     :: a, b, c             ! three sides
   REAL     :: s                   ! half of perimeter
   REAL     :: Area                ! triangle area
   LOGICAL  :: Cond_1, Cond_2      ! two logical conditions

   READ(*,*)  a, b, c

   WRITE(*,*)  "a = ", a
   WRITE(*,*)  "b = ", b
   WRITE(*,*)  "c = ", c

   Cond_1 = (a > 0.) .AND. (b > 0.) .AND. (c > 0.0)
   Cond_2 = (a+b > c) .AND. (a+c > b) .AND. (b+c > a)
   IF (Cond_1 .AND. Cond_2) THEN
      s    = (a + b + c) / 2.0
      Area = SQRT(s*(s-a)*(s-b)*(s-c))
      WRITE(*,*) "Triangle area = ", Area
      WRITE(*,*) "ERROR: this is not a triangle!"

END PROGRAM  HeronFormula
Click here to download this program.

Program Input and Output


Here is the box trick of this program.

a, b and c form a triangle computes s and its area
displays an error message