let i = -1;
let total = 0;
let numPrompt;
do {
numPrompt = prompt("")
total += parseInt(numPrompt)
i++;
}
while (numPrompt != '0'); // do-while loop
let avg = total/i;
console.log(total)
console.log(avg)
I want user to input a number each time till they input zero which will output all their previous input, total and average.
I declare i = -1 to avoid counting the last input which is the zero.
in my code, I only manage to display the total of all my input but what I also want is all my previous inputs (prompt)printed out each row
You can use an array, which stores a list of things:
let i = 0;
let total = 0;
let numPrompt;
let numbers = [];
do {
numPrompt = prompt("")
total += parseInt(numPrompt)
if (numPrompt != '0') {
numbers.push(numPrompt);
i++;
}
} while (numPrompt != '0'); // do-while loop
let avg = total / i;
console.log(total)
console.log(avg)
console.log(numbers);
Setting i
to -1 is a bit of a workaround -- the above code starts it at 0 and checks if the inputted number is 0 before incrementing it.