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
Release: 2024-11-12 05:42:02
Original
604 people have browsed it

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}`);
Copy after login

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}`);
Copy after login

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!

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