Simple algorithm to determine the type of a triangle, being informed its sides

## Introduction

Triangles are classified depending on relative sizes of their elements.

As regard their sides, triangles may be:

- Scalene (all sides are different)
- Isosceles (two sides are equal)
- Equilateral (all three sides are equal)

And as regard their angles, triangles may be:

- Acute (all angles are acute)
- Right (one angle is right)
- Obtuse (one angle is obtuse)

In this tip we will develop an algorithm that determines the type of a triangle, given its sides.

## Using the code

The algorithm below was implemented in the Lua language using the ZeroBrane Studio IDE:

Hide Shrink Copy Code

```
local function triangleType(a,b,c)
local bySide,byAngle = nil
if (a < (b + c) and b < (a + c) and c < (a + b)) then
--Type of the triangle by sides
if ( a == b and b == c ) then
bySide = 1 -- Equilateral
elseif (a == b or b == c or a == c) then
bySide = 2 -- Isosceles
else
bySide = 3 -- Scalene
end
--Type of the triangle by Angle
if (a^2 == b^2 + c^2) or (b^2 == a^2 + c^2) or (c^2 == a^2 + b^2) then
byAngle = 1 -- Right
elseif (a^2 > b^2 + c^2) or (b^2 > a^2 + c^2) or (c^2 > a^2 + b^2) then
byAngle = 2 -- Obtuse
else
byAngle = 3 -- Acute
end
end
return bySide,byAngle
end
local bySideTypes = {"Equilateral","Isosceles","Scalene"}
local byAngleTypes = {"Right","Obtuse","Acute"}
print("Triangle Type\n")
print("Enter the value of A side: ")
local a = tonumber(io.read())
print("Enter the value of B side: ")
local b = tonumber(io.read())
print("Enter the value of C side: ")
local c = tonumber(io.read())
local bySide,byAngle = triangleType(a,b,c)
if (bySide ~= nil) then
print ("The type of the triangle is " .. bySideTypes[bySide] .. " and " .. byAngleTypes[byAngle])
else
print ("These sides do not form a triangle")
end
```

## Points of Interest

The following points should be taken into account for the understanding of the algorithm:

- The sum of the lengths of
**any**two**sides of a triangle**is greater than the length of the third**side** - To obtain the type of the triangle according to its angles, we use the Pythagorean theorem
- In the Lua language, a function can return more than one value.
- For the sake of “good practices”, we have resolved to encode the types of triangles in an array

## References

- https://study.com/academy/lesson/types-of-triangles-their-properties.html
- https://www.youtube.com/watch?v=I2Lt-jU3IJc

## Conclusion

The source code for this algorithm is available on GitHub at: MathAlgorithms

That’s all, folks!