JavaScript How To Find The Average Of 10 Numbers Using A While Loop
You can find the average of 10 numbers in JavaScript using a while loop by following these steps..
- Initialize variables to keep track of the sum and count of the numbers.
- Use a while loop to repeatedly prompt the user for input until you have received 10 numbers.
- Inside the loop, add each input number to the sum and increment the count.
- After the loop, calculate the average by dividing the sum by the count.
Here's an example JavaScript code that demonstrates this:
let sum = 0;
let count = 0;
while (count < 10) {
const input = prompt(`Enter number ${count + 1}:`);
const number = parseFloat(input);
if (!isNaN(number)) {
sum += number;
count++;
} else {
alert("Invalid input. Please enter a valid number.");
}
}
if (count > 0) {
const average = sum / count;
alert(`The average of the 10 numbers is: ${average}`);
} else {
alert("No valid numbers entered.");
}