Kotlin Function: Calculate the average of variable number of arguments
Write a Kotlin function that takes a variable number of arguments (varargs) and calculates the average of those numbers.
Pre-Knowledge (Before you start!)
- Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
- Kotlin Functions: Understanding how to define and call functions in Kotlin.
- Varargs in Kotlin: Knowledge of using the vararg keyword to accept a variable number of arguments in a function.
- Arithmetic Operations: Ability to perform addition and division to calculate the sum and average of numbers.
- Array Operations: Awareness of methods like sum() and properties like size for working with arrays or collections.
- Printing Output: Familiarity with the println() function to display output on the screen.
Hints (Try before looking at the solution!)
- Define the Function.
- Calculate the Sum.
- Calculate the Average.
- Handle Edge Cases.
- Call the Function.
- Display the Output.
- Common Errors to Avoid:
- Forgetting edge cases like no arguments.
- Misplacing sum or size logic.
- Not testing with varied inputs.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics