Search code examples
javascriptdo-loops

How do I add inputs together in a do while loop?


hi im very new to javascript and stuck doing my homework. My question is how do I add multiple inputs together in a do while loop? I am supposed to get all the inputs added together then divided by the amount of inputs to get the average. For example if the user were to input 7, 3, 5 and 2 then the answer will be 4.25.This is what I have so far.

var prompt;
var input = prompt("Please enter a number, input a negative number to  stop");
var number = input >= 0;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
    input = +prompt("Error enter a positive number to start");
}
do {
    input = +prompt("Enter another number, a negative to stop");
    sum += number;
    //inputs added together goes here
}     while (input >= 0);
alert(); //inputs added together divided by sum goes here

Solution

  • Hi try this version;

    var num = 0, sum = 0, count = 0; 
    do { 
    num = parseInt(prompt('Enter Number')); 
    sum = num >= 0 ? sum+=num : sum; 
    count = num >= 0 ? count+=1: count; } 
    while(num >= 0);
    console.log(sum + ' count is ' + count);
    console.log(sum/count);
    

    Basically I read from prompt, convert the input to integer, I sum the numbers if they are 0 or greater. I add 1 to the count if number is 0 or greater then I divide the sum by the count