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

In Flutter, you can find the average of 10 numbers using a while loop as well. Here's a Dart code example that demonstrates how to do this:

import 'dart:io';

void main() {
  double sum = 0;
  int count = 0;

  while (count < 10) {
    stdout.write("Enter number ${count + 1}: ");
    String input = stdin.readLineSync();
    double number = double.tryParse(input);

    if (number != null) {
      sum += number;
      count++;
    } else {
      print("Invalid input. Please enter a valid number.");
    }
  }

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

  • We import the dart:io library to handle input and output.
  • 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 numbers.
  • Inside the loop, we read input from the user and attempt to parse it into a double. If the input is a valid number, we add it to the sum and increment the count. If the input is not a valid number, we print an error message.
  • After the loop, we calculate the average by dividing the sum by the count and display the result.