Given an array “arr” of size N, the task is to calculate the average of all the elements of the given array.
Example:
Input: arr = {1, 2, 3, 4, 5}
Output: 3
Explanation: (1+2+3+4+5) / 5 = 15/5 = 3
These are the following approaches:
Table of Content
Approach 1: Using for loop
This JavaScript program defines a function to calculate the average of elements in an array. It iterates through each element, sums them up, and divides the total by the number of elements. Finally, it returns the average value.
Example: This example shows the implementation of the above-explained approach.
function calAvg(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
} const arr = [10, 20, 30, 40, 50]; const average = calAvg(arr); console.log( "Average:" , average);
|
Average: 30
Approach 2: Using a while loop
Here we define a function to calculate the average of elements in an array using a while loop. It initializes a sum variable, iterates through each element with an index variable, updates the sum, and finally divides it by the array length to compute the average.
Example: This example shows the implementation of the above-explained approach.
function calculateAverage(arr) {
let sum = 0;
let i = 0;
while (i < arr.length) {
sum += arr[i];
i++;
}
return sum / arr.length;
} const arr = [10, 20, 30, 40, 50]; const average = calculateAverage(arr); console.log( "Average:" , average);
|
Average: 30