How to calculate the area of a circle in Scala
Overview
The area of a circle is the region occupied by the circle. It is the product of pi (π) and the square of the circle’s radius. To do this, we need to create a constant variable pi that will hold our pi value. Then we multiply this value by the square of the radius. We need to use the Math.pow() method to calculate the squared value of the radius. To do this, we need to import the scala.math library.
Syntax
pi * Math.pow(radius, 2)
Syntax for finding the area of a circle in Scala
Parameters
pi: This is the pi constant variable.
radius: This is the given radius of the circle.
Return value
A float value is returned, which is the area of the circle.
Example
// import math packageimport scala.math._object Main extends App {// create a constantval PI = 3.14F// create some radiivar radius1 = 5var radius2 = 3.5Fvar radius3 = 20var radius4 = 4// get area of circlesvar area1 = PI * Math.pow(radius1, 2)var area2 = PI * Math.pow(radius2, 2)var area3 = PI * Math.pow(radius3, 2)var area4 = PI * Math.pow(radius4, 2)// print valuesprintln(area1)println(area2)println(area3)println(area4)}
Explanation
- Line 2: We import the
mathmodule. - Line 6: We create a
PIvalue. - Line 9–12: We create some radii.
- Line 15–18: We get the area of some circles.
- Line 21–24: We print the areas to the console.