Actually, your provided code asks for 3 inputs within each cycle of the while()
loop. Therefore, if you are only asking for 3 numbers, then you will not need the while()
loop.
I've written a really basic set of codes below with 2 functions which find the maximum and the minimum value in the array.
var totalSum = 0;
// initialize the array with 0s.
var inputNums = [0, 0, 0];
// Loop through the input number array and ask for a number each time.
for (var i = 0; i < inputNums.length; i++) {
inputNums[i] = parseInt(prompt("Enter Number #" + (i + 1)));
//Add the number to the total sum
totalSum = totalSum + inputNums[i];
}
// Calculate results
var average = totalSum / inputNums.length;
document.write("Total Inputs: " + inputNums.length + "<br>");
document.write("Sum: " + totalSum + "<br>");
document.write("Average: " + average + "<br>");
document.write("Max: " + findMaxValue(inputNums) + "<br>");
document.write("Min: " + findMinValue(inputNums) + "<br>");
function findMaxValue(numArray) {
// Initialize with first element in the array
var result = numArray[0];
for(var i = 1; i < numArray.length; i++) {
// loops through each element in the array and stores it if it is the largest
if(result < numArray[i]) {
result = numArray[i];
}
}
return result;
}
function findMinValue(numArray) {
// Initialize with first element in the array
var result = numArray[0];
for(var i = 1; i < numArray.length; i++) {
// loops through each element in the array and stores it if it is the smallest
if(result > numArray[i]) {
result = numArray[i];
}
}
return result;
}
Unfortunately the snippet system in SO does not support prompt()
.
I've put up a jsfiddle here: https://jsfiddle.net/hrt7b0jb/