Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum up all numbers entered in prompt

var num = prompt("Enter a number");

for (var sum = 0; sum <= num; sum++) {
  sum = sum + 1;
}
document.write(sum);

example when I enter 6 in the prompt it will sum 1+2+3+4+5+6 =21. but as of right now i can only print 123456 instead of 21.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem with your code is that you’re using sum for the loop and for the answer. That’s messing everything up. You can use a variable for the loop and another variable for the sum.

Maybe that works for you.

var num = prompt("Enter a number");
var sum = 0;
for(var i = 1; i <= num; i++) {
    sum += i;
}
document.write(sum);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading