Kotlin function: Calculate circle area with default pi
Write a Kotlin function that calculates the area of a circle. Use a default value of 3.14 for pi.
Sample Solution:
Kotlin Code:
fun calculateCircleArea(radius: Double, pi: Double = 3.14): Double {
return pi * radius * radius
}
fun main() {
val radius = 4.0
val area = calculateCircleArea(radius)
println("The area of the circle with radius $radius is $area")
}
Sample Output:
The area of the circle with radius 4.0 is 50.24
Explanation:
In the above function -
- The "calculateCircleArea()" function takes two parameters: radius (representing the circle radius) and pi (representing the value of pi). The pi parameter has a default value of 3.14.
- Within the function, the circle area is calculated by multiplying the square of the radius by pi.
- The calculated area is returned as a Double value.
- In the "main()" function, a sample radius of 5.0 is defined.
- The "calculateCircleArea()" function is called with the radius as an argument, and the result is stored in the area variable.
- The circle area is then printed to the console using string interpolation.
Kotlin Editor:
Previous: Calculate Body Mass Index (BMI).
Next: Print person details with named arguments.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics