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.

Solution

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

PROGRAM  HeronFormula
   IMPLICIT  NONE

   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
   WRITE(*,*)

   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
   ELSE
      WRITE(*,*) "ERROR: this is not a triangle!"
   END IF

END PROGRAM  HeronFormula
Click here to download this program.

Program Input and Output

Discussion

Here is the box trick of this program.

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