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.

Javascript
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

Similar Reads

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....

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....

Using reduce() method

The approach sums array elements with reduce(), divides by array length for average. Utilizes reduce’s accumulator to compute total sum, then divides by array length to derive average value....

Using forEach method

This method uses the forEach method to iterate over the array and sum the elements. Then we calculate the average by dividing the sum by the number of elements in the array....