Sum until break

Hello,

I’m tryin to run a total of prompt numbers until -1 is entered. The total should not include the the -1 in the sum. Any help is appreciated.

var s = 0;
var t = 0;
var p = 0;
  while (p<0);
   {
var number = prompt("Enter a positive number to be added to the total or -1 to end. ");
       t += parseInt(number);
       t++;
      console.log("Enter a positive number to be added to the total or -1 to end. " + number);
   }
{
   console.log("The sum of all numbers entered is " + t);

}
var s = 0;
var t = 0;
var p = 0;
while (p < 0); {
  var number = prompt("Enter a positive number to be added to the total or -1 to end. ");
  t += parseInt(number);
  t++;
  console.log("Enter a positive number to be added to the total or -1 to end. " + number);
}
{
  console.log("The sum of all numbers entered is " + t);
}

I made some style edits to make it easier to see what’s happening.

while (p < 0); {

This right here is a big problem. You’ve broken up the while syntax with a ;, which basically means you told the loop to have an empty body.

Also, p is never < 0, so your loop body will never run.

Also, p is never changed, so if you loop runs, it will never stop.

Also, I’m not sure why you have this line:

  t++;

We are not in the era of punchcards, so I strongly recommend that you use full words for your variable names.

1 Like

These are the things that jump out at me:

  • Your while loop will never run because p is 0 at the beginning.
  • You are never modifying the value of p. (This would cause an infinite loop if the loop ran.)
  • You are not checking for your sentinel value (-1).
  • Your variables aren’t named, so I don’t know what you’re intending to do with each.
  • You are always adding 1 to t.
  • You have an unused variable (s).
2 Likes

This challenge is similar to my first challenge, except I don’t want i to stop @ 10 prompts. I want it to stop @ -1 but not add the -1 to the sum.

var i = 0;
total = 0;
   while(i<10)
   {
       var number = prompt("Enter a positive number to be added to the total or -1 to end. ");
       total += parseInt(number);
       i++;
     console.log("Enter a positive number to be added to the total or -1 to end. " + number);
   }
{
   console.log("The sum of all numbers entered is " + total);

}

Well then I think you’d need to know the last number that was selected, in the scope of the while. One option would be to declare a variable outside the while to store the last selection and use that in the while check.