Home >Web Front-end >JS Tutorial >How do I calculate the sum and average of elements in an array?

How do I calculate the sum and average of elements in an array?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 05:42:02631browse

How do I calculate the sum and average of elements in an array?

Calculating Sum and Average of Array Elements

To compute the sum and average of an array's elements, follow these steps:

Summation:

  1. Initialize a variable to store the sum (sum = 0).
  2. Iterate through the array, adding each element to the sum variable.
  3. The final value of sum will be the sum of all array elements.

Example:

const elmt = [0, 1, 2, 3, 4, 7, 8, 9, 10, 11];
let sum = 0;

for (i = 0; i < elmt.length; i++) {
  sum += elmt[i];
}

console.log(`The sum is: ${sum}`);

Averaging:

  1. Calculate the sum of elements as described above.
  2. Divide the sum by the total number of elements (avg = sum / array_length) to obtain the average.

Example:

const avg = sum / elmt.length;
console.log(`The average is: ${avg}`);

The above is the detailed content of How do I calculate the sum and average of elements in an array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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