Open In App

R Program to Calculate the Area of a Triangle

In this article, we will discuss how to calculate the Area of a Triangle with its working example in the R programming language. Calculating the area of a triangle is a fundamental geometric task. The area of a triangle can be computed using the base and height of the triangle or by using the lengths of its sides and the semi-perimeter. In this R program, we will explore how to calculate the area of a triangle using the base and height methods.

Syntax:

# Calculate the area of the triangle
area <- 0.5 * base * height
# Print the result
cat("The area of the triangle is:", area)

Example 1:




# Values for base and height
base <- 10
height <- 5
 
# Calculate the area of the triangle
area <- 0.5 * base * height
 
# Print the result
cat("The area of the triangle is:", area)

Output:



The area of the triangle is: 25

Example 2:




# Values for base and height
base <- 10
height <- 10
 
# Calculate the area of the triangle
area <- 0.5 * base * height
 
# Print the result
cat("The area of the triangle is:", area)

Output:

The area of the triangle is: 50

Example 3: R Program to Calculate the Area of a Triangle using Side Lengths




# Function to calculate the area of a triangle using side lengths
calculateTriangleArea <- function(a, b, c) {
  s <- (a + b + c) / 2
  area <- sqrt(s * (s - a) * (s - b) * (s - c))
  return(area)
}
 
# Input: Lengths of the three sides of the triangle
a <- 5
b <- 5
c <- 5
 
# Calculate the area using the function
triangleArea <- calculateTriangleArea(a, b, c)
 
# Display the result
cat("\nThe area of the triangle with side lengths", a, b, c, "is:", triangleArea, "\n")

Output:



The area of the triangle with side lengths 5 5 5 is: 10.82532 


Article Tags :