Kotlin Function: Calculate the average of variable number of arguments
Kotlin Function: Exercise-18 with Solution
Write a Kotlin function that takes a variable number of arguments (varargs) and calculates the average of those numbers.
Sample Solution:
Kotlin Code:
fun calculateAverage(vararg numbers: Double): Double {
val sum = numbers.sum()
return sum / numbers.size
}
fun main() {
val average1 = calculateAverage(1.0, 2.0, 6.0)
println("Average 1: $average1")
val average2 = calculateAverage(-10.0, -20.0, 30.0, 40.0, 50.0)
println("Average 2: $average2")
}
Sample Output:
Average 1: 3.0 Average 2: 18.0
Explanation:
In the above exercise -
- The "calculateAverage()" function is defined with a variable number of arguments using the vararg keyword. It takes multiple Double values as input.
- Inside the function, the sum variable is assigned the sum of all the numbers using the sum function available for arrays or collections. Then, the average is calculated by dividing the sum by the number of elements. This is obtained using the size property of the numbers array.
- In the "main()" function, we demonstrate the calculateAverage function by passing different sets of numbers as arguments. The calculated averages are stored in variables average1 and average2, respectively. Finally, we print the average values using println() function.
Kotlin Editor:
Previous: Check Prime Number, Return Boolean.
Next: Check if the number is divisible.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/function/kotlin-function-exercise-18.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics