w3resource

Kotlin function: Calculate Body Mass Index (BMI)


Write a Kotlin function that calculates the Body Mass Index (BMI) of a person. The function should take the height (in meters) and weight (in kilograms) as arguments. Use default arguments for height and weight.


Pre-Knowledge (Before you start!)

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

Hints (Try before looking at the solution!)

  • Define the Function.
  • Validate Inputs.
  • Calculate BMI.
  • Call the Function.
  • Display the Output.
  • Test with Different Values.
  • Common Errors to Avoid:
    • Forgetting input validation.
    • Misplacing the BMI formula.
    • Not handling default values correctly.

Sample Solution:

Kotlin Code:

fun calculateBMI(height: Double = 0.0, weight: Double = 0.0): Double {
    require(height > 0.0) { "Height must be greater than 0." }
    require(weight > 0.0) { "Weight must be greater than 0." }

    val bmi = weight / (height * height)
    return bmi
}

fun main() {
    val height = 1.65
    val weight = 63.5
    val bmi = calculateBMI(height, weight)
    println("BMI: $bmi")
}

Sample Output:

BMI: 23.32415059687787

Explanation:

In the above exercise -

  • The "calculateBMI()" function is defined with two parameters: height (default value of 0.0) and weight (default value of 0.0). These parameters represent height in meters and weight in kilograms, respectively.
  • The require function validates that the provided height and weight are greater than 0. If either requirement fails, an exception is thrown with the corresponding error message.
  • The BMI is calculated using the formula weight / (height * height).
  • The calculated BMI is returned from the function.
  • In the "main()" function, a sample height of 1.65 meters and 63.5 kilograms is provided. The calculateBMI function is called with these values, and the resulting BMI is printed to the console.

Go to:


PREV : Calculate area of rectangle with default Values.
NEXT : Calculate circle area with default pi.

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.