w3resource

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.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Default Arguments.
  • Arithmetic Operations.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Calculate the Area.
  • Call the Function.
  • Display the Output.
  • Test with Different Values.
  • Common Errors to Avoid:
    • Forgetting default values.
    • Misplacing the formula.
    • Not validating negative radius.

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.

Go to:


PREV : Calculate Body Mass Index (BMI).
NEXT : Print person details with named arguments.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.