Kotlin How To Find The Average Of 10 Numbers Using A While Loop
To find the average of 10 numbers in Kotlin using a while loop, you can follow these steps..
- Initialize variables to keep track of the sum and count of numbers.
- Use a while loop to repeatedly prompt the user for input until you have received 10 numbers.
- Inside the loop, add each input number to the sum and increment the count.
- After the loop, calculate the average by dividing the sum by the count.
Here's an example Kotlin code that demonstrates this:
fun main() {
var sum = 0.0
var count = 0
while (count < 10) {
print("Enter number ${count + 1}: ")
val input = readLine()
val number = input?.toDouble()
if (number != null) {
sum += number
count++
} else {
println("Invalid input. Please enter a valid number.")
}
}
if (count > 0) {
val average = sum / count
println("The average of the 10 numbers is: $average")
} else {
println("No valid numbers entered.")
}
}