Home > Web Front-end > JS Tutorial > How to Calculate the Sum and Average of Elements in an Array?

How to Calculate the Sum and Average of Elements in an Array?

Mary-Kate Olsen
Release: 2024-11-10 10:37:02
Original
279 people have browsed it

How to Calculate the Sum and Average of Elements in an Array?

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/>");
Copy after login

In this example:

  • We create variables for the sum, average, and the count of elements in the array.
  • We iterate through the array elements, converting each from a string to an integer to ensure numerical accuracy.
  • We calculate the sum by accumulating the elements.
  • Finally, we compute the average by dividing the sum by the total count.
  • We display the results in an HTML document using document.write().

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template