How to use a while loop In Javascript
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);
Output
Average: 30
JavaScript Program to Calculate the Average of All the Elements Present in an Array
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
- Using for loop
- Using a while loop
- Using reduce() method
- Using forEach method