Swift How To Find The Average Of 10 Numbers Using A While Loop

You can find the average of 10 numbers in Swift using a while loop as follows..

import Foundation

var sum = 0.0
var count = 0

while count < 10 {
    print("Enter number \(count + 1):", terminator: " ")
    if let input = readLine(), let number = Double(input) {
        sum += number
        count += 1
    } else {
        print("Invalid input. Please enter a valid number.")
    }
}

if count > 0 {
    let average = sum / Double(count)
    print("The average of the 10 numbers is: \(average)")
} else {
    print("No valid numbers entered.")
}

In this Swift code:

  • We import the Foundation framework to use readLine() for input.
  • We initialize variables to keep track of the sum and count of numbers.
  • We use a while loop to repeatedly prompt the user for input until they have entered 10 valid numbers.
  • Inside the loop, we check if the input is a valid number using Double(input). If it's a valid number, we add it to the sum and increment the count. If not, we print an error message.
  • After the loop, we calculate the average by dividing the sum by the count and display the result.