Table of contents
This was code Wars kata problem.
Here is the question:
DESCRIPTION:
Write a function that calculates the average of the numbers in a given list.
Note: Empty arrays should return 0.
Solution
First, we have to determine the sum of the total elements in the array.
We will create a variable to store our sum values in and initialize it:
let sum = 0;
We then have to find the sum of the elements of the array by creating a loop that iterates through the array adding each number as it passes by and pushing it to our already declared variable.
Our variable; sum, stores the total summation value of the array.
for (let i = 0; i < array.length; i++ ) {
sum += array[i];
}
We then have to ensure that a null array returns 0 and an array with elements returns the average and since we have the sum of the array, we can just divide it by the number of elements in the array.
We can do this by checking if there are no elements and returning 0,
if (array.length>0){
return sum/array.length
}
else
return 0;
}
Putting it together:
function findAverage(array) {
// create a variable for the sum and initialize it
let sum = 0;
// iterate over each item in the array
for (let i = 0; i < array.length; i++ ) {
sum += array[i];
}
if (array.length>0){
return sum/array.length
}
else
return 0;
}