Average or Arithmetic mean is a representation of a set of numbers by a single number. Its value can be obtained by calculating the sum of all the values in a set and dividing the sum by the number of values.
Consider the following set of numbers: 1, 2, 3 & 4
Average/Mean = (1+2+3+4)/4
An array is a container object that holds a fixed number of values of a single type. An array’s length, once created, would remain constant/fixed.
You can go through other basic concepts of object-oriented programming such as looping, conditional statements, user-defined functions, and classes to understand this blog better.
Table of Contents
Simple approach to finding the average of an arrayWe would first count the total number of elements in an array followed by calculating the sum of these elements and then dividing the obtained sum by the total number of values to get the Average / Arithmetic mean
Breaking down the array average algorithmMean of an array can be obtained in 3 steps:
Step 1: Finding the total number of elements in an array (basically, its length)
This can be obtained by calculating the length of the array using the length method.
Step 2: Finding the sum of all the elements of an array (sum)
We would need to traverse the array to find the sum. We initialize a variable called ‘total’ and loop over the array and add each element of the array to the ‘total’ variable
Step 3: Dividing the values obtained in Step 1 & 2.(sum/length)