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

To find the average of 10 numbers in Ruby 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.
sum = 0
count = 0

while count < 10
  print "Enter number #{count + 1}: "
  input = gets.chomp
  number = input.to_f

  if number.to_s == input
    sum += number
    count += 1
  else
    puts "Invalid input. Please enter a valid number."
  end
end

if count > 0
  average = sum / count
  puts "The average of the 10 numbers is: #{average}"
else
  puts "No valid numbers entered."
end