OneBite.Dev - Coding blog in a bite size

Find The Average Of All Elements In An Array In Dart

Code snippet for how to Find The Average Of All Elements In An Array In Dart with sample and detail explanation

In the world of software engineering, finding the average of all elements in an array is a widely used operation. Among many other languages, Dart offers a simple and effective way to perform this operation.

Code snippet for Finding The Average Of All Elements In An Array In Dart

void main() { 
  List<int> numbers = [2, 4, 6, 8, 10];   
  int total = 0;
  
  for(int i = 0; i<numbers.length; i++) {
    total += numbers[i];
  }
  double average = total / numbers.length;
  print('The average is $average');
}

Code Explanation for Finding The Average Of All Elements In An Array In Dart

This Dart program calculates the average of all elements in an array. Let’s understand the code step by step.

  1. First, we define the main function where the program execution will start.
void main() {  
}
  1. We define an array of integers using the List keyword. These numbers represent the elements of the array for which we will calculate the average.
List<int> numbers = [2, 4, 6, 8, 10];  
  1. Next, we define a variable ‘total’ that will store the sum of all array elements. Initially, it is set to 0.
int total = 0;
  1. We then loop over each element of the array using a for loop. In each iteration, we add the value of the current array element to ‘total’.
for(int i = 0; i<numbers.length; i++) {
  total += numbers[i];
}
  1. After the for loop finishes execution, ‘total’ stores the sum of all array elements. We then calculate the average by dividing ‘total’ by the number of array elements (i.e., numbers.length).
double average = total / numbers.length;
  1. Finally, we print the average.
print('The average is $average');

This is how you can easily find the average of all elements in an array using the Dart programming language.

dart