Calculating the Sum and Average of Array Elements
To compute the sum and average of elements in an array, utilize simple mathematical operations. Begin by defining the variables to hold the sum and average. Then, iterate through the array, accumulating the sum by adding each element. Finally, calculate the average by dividing the sum by the number of elements in the array.
Consider the following code:
var sum = 0; var average = 0; var count = elmt.length; for (i = 0; i < count; i++) { sum += parseInt(elmt[i]); // Convert string elements to integers for numerical operations } average = sum / count; document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + average + "<br/>");
In this example:
This approach allows you to handle integer or floating-point elements in an array and obtain the collective sum and average efficiently.
The above is the detailed content of How to Calculate the Sum and Average of Elements in an Array?. For more information, please follow other related articles on the PHP Chinese website!