Home > Mobile >  how do I store my prompt input and display all of it when I input zero
how do I store my prompt input and display all of it when I input zero

Time:11-05


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

CodePudding user response:

If you want to store all of your previous inputs, use an array.

let a=[], i, t;
while((i= prompt())!==0) a.push(i);
console.log(`inputs: ${a}, total: ${t=a.reduce((a,c)=>a c)}, avg: ${t/a.length}`);

CodePudding user response:

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.

  • Related