Kotlin Function: Calculate area of rectangle with default Values
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.
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 multiplication logic.
- Not validating negative inputs.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics