EXERCISE - 2
Program, to find the area of rectangle, square, circle and triangle by accepting suitable
input parameters from the user.
PROGRAM CODE :
# Function to calculate the area of a rectangle
rectangle_area <- function(length, width) {
return(length * width)
}
# Function to calculate the area of a square
square_area <- function(side) {
return(side * side)
}
# Function to calculate the area of a circle
circle_area <- function(radius) {
return(pi * radius^2)
}
# Function to calculate the area of a triangle
triangle_area <- function(base, height) {
return(0.5 * base * height)
}
# Main program
while (TRUE) {
cat("Select a shape to calculate its area:\n")
cat("1. Rectangle\n")
cat("2. Square\n")
cat("3. Circle\n")
cat("4. Triangle\n")
cat("5. Exit\n")
choice <- as.integer(readline(prompt = "Enter your choice (1-5): "))
if (choice == 1) {
length <- as.numeric(readline(prompt = "Enter the length of the
rectangle: "))
width <- as.numeric(readline(prompt = "Enter the width of the
rectangle: "))
area <- rectangle_area(length, width)
cat("Area of the rectangle:", area, "\n")
} else if (choice == 2) {
side <- as.numeric(readline(prompt = "Enter the side of the square: "))
area <- square_area(side)
cat("Area of the square:", area, "\n")
} else if (choice == 3) {
radius <- as.numeric(readline(prompt = "Enter the radius of the circle:
"))
area <- circle_area(radius)
cat("Area of the circle:", area, "\n")
} else if (choice == 4) {
base <- as.numeric(readline(prompt = "Enter the base of the triangle:
"))
height <- as.numeric(readline(prompt = "Enter the height of the
triangle: "))
area <- triangle_area(base, height)
cat("Area of the triangle:", area, "\n")
} else if (choice == 5) {
break
} else {
cat("Invalid choice. Please try again.\n")
}
}
SAMPLE OUTPUT :
Select a shape to calculate its area:
1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 1
Enter the length of the rectangle: 56
Enter the width of the rectangle: 47
Area of the rectangle: 2632
Select a shape to calculate its area:
1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 2
Enter the side of the square: 48
Area of the square: 2304
Select a shape to calculate its area:
1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 3
Enter the radius of the circle: 5
Area of the circle: 78.53982
Select a shape to calculate its area:
1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 4
Enter the base of the triangle: 26
Enter the height of the triangle: 48
Area of the triangle: 624
Select a shape to calculate its area:
1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 5