1. Introduction
The area of a circle is a fundamental concept in geometry, given by the formula A = πr^2, where A is the area and r is the circle's radius. In this blog post, we'll create a Scala program to calculate and display the area of a circle given its radius.
2. Program Steps
1. Set up the Scala environment.
2. Create an object to house the main function.
3. Define the radius of the circle.
4. Implement a function to calculate the area of the circle.
5. Call the area-calculating function and display the result.
6. Run the program.
3. Code Program
object CircleAreaApp {
def main(args: Array[String]): Unit = {
// Define the radius of the circle
val radius = 5.0
println(s"Calculating the area of a circle with radius: $radius units")
// Calculate and print the area using the circleArea function
val area = circleArea(radius)
println(s"\nThe area of the circle is: $area square units")
}
// Function to calculate the area of a circle
def circleArea(r: Double): Double = {
val Pi = 3.141592653589793
Pi * r * r
}
}
Output:
Calculating the area of a circle with radius: 5.0 units The area of the circle is: 78.53981633974483 square units
Explanation:
1. We commence with an object named CircleAreaApp. In Scala, the main method, acting as the entry point of the program, is found within an object.
2. Within the main function, we define a value radius representing the radius of the circle.
3. The user is informed about the radius being used via a print statement.
4. We use a separate function named circleArea to calculate the area of the circle. This function accepts a radius and returns the area by using the aforementioned formula.
5. Within the main function, we call circleArea to get the area and subsequently print the result.
6. The output shows the program first indicating the radius of the circle, and then it provides the calculated area.
Comments
Post a Comment