var msg = "";
var num = 0;
var sum = 0;
var avg = 0;
for (var x = 1; x <= 5; x++)
{
num = prompt("This script calculates the average of 5 numbers", "Number " + x);
num = parseInt(num);
sum = sum + num;
}
avg = sum / 5;
alert("The average of the 5 numbers is " + avg);
After initializing all the required variables, we run a for loop five times to gather input from the visitor. The input is then converted to a number through parseInt() and added to the variable sum. At the end, the average is calculated and displayed in an alert box.
var msg = "";
var num = 0;
var sum = 0;
var avg = 0;
var t = prompt("For how many numbers would you like to find the average?", "");
t = parseInt(t);
for (var x = 1; x <= t; x++)
{
num = prompt("This script calculates the average of 5 numbers", "Number " + x);
num = parseInt(num);
sum = sum + num;
}
avg = sum / t;
alert("The average is " + avg);
A modification of the above script. We introduce a prompt() at the very beginning through which we get the total number of numbers. This value is used in the for loop to generate the requisite number of prompts and is also used in the calculation of the average.