w3resource

Kotlin Function: Calculate area of rectangle with default Values

Kotlin Function: Exercise-7 with Solution

Write a Kotlin function that calculates and returns the area of a rectangle. It should take 'length' and 'width' as arguments, with default values of 0.0.

Sample Solution:

Kotlin Code:

fun calculateArea(length: Double = 0.0, width: Double = 0.0): Double {
    return length * width
}

fun main() {
    val area = calculateArea(7.0, 3.0)
    println("The area of the rectangle is: $area")
}

Sample Output:

The area of the rectangle is: 21.0

Explanation:

In the above exercise -

  • The "calculateArea()" function takes two parameters: length and width, both of type Double. These parameters have default values of 0.0, which means they can be omitted when calling the function.
  • Inside the function, it calculates the rectangle area by multiplying the length and width values. The result is then returned as a Double value.
  • In the "main()" function, we call the "calculateArea()" function with a length of 7.0 and width of 3.0. The returned area value is stored in the area variable, and then printed using println() function.

Kotlin Editor:


Previous: Print message without return.
Next: Check number divisibility by 7.

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.