R Program to Calculate Area of a Triangle

1. Introduction

Knowing how to compute the area of a triangle is fundamental in geometry and holds importance in various other fields. In this tutorial, we will devise an R program that calculates the area of a triangle using its base and height.

2. Program Goal

The main objective of the program is to prompt the user to input the base and height of the triangle. 

The program will then compute the area using the provided measurements and display the result.

3. Code Program

# Prompt the user to enter the base of the triangle
cat("Enter the base of the triangle: ")
base <- as.numeric(readLines(n=1))

# Prompt the user to enter the height of the triangle
cat("Enter the height of the triangle: ")
height <- as.numeric(readLines(n=1))

# Calculate the area of the triangle
area <- 0.5 * base * height

# Display the computed area to the user
cat("The area of the triangle with base", base, "and height", height, "is:", area, "\n")

Output:

Enter the base of the triangle: 8
Enter the height of the triangle: 6
The area of the triangle with base 8 and height 6 is: 24

4. Step By Step Explanation

1. The program begins by requesting the user to provide the base of the triangle using the cat function.

cat("Enter the base of the triangle: ")

2. The user's input is captured using readLines(n=1), converted into a numeric value via as.numeric, and stored in the base variable.

base <- as.numeric(readLines(n=1))

3. Similarly, the user is prompted to indicate the height of the triangle. This input is captured, transformed to a numeric format, and assigned to the height variable.

# Prompt the user to enter the height of the triangle
cat("Enter the height of the triangle: ")
height <- as.numeric(readLines(n=1))

4. With the base and height acquired, the program calculates the area of the triangle. This computed value is stored in the area variable.

# Calculate the area of the triangle
area <- 0.5 * base * height

5. Finally, the program uses the cat function to show the user the calculated area of the triangle based on their supplied measurements.

cat("The area of the triangle with base", base, "and height", height, "is:", area, "\n")

Comments