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

Sum of n Natural numbers using for loop

The question is to calculate the sum of ten natural numbers but the code isn’t working.

<!DOCTYPE html>
<html>
<head>
    <title>Sum of first 10 Natural numbers</title>
</head>
<body>
    <script>
       var sum = 0, n;
       parseInt (prompt("Enter the number: "));
       for (let i = 0; i <= n; i++) {
        sum += i; 
       }
       alert ("Sum of Numbers: " + sum);
    </script>
    
</body>
</html> 

>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 reason your code was not working is because you were not saving the value from prompt in a variable.

var sum = 0, n;
n = parseInt (prompt("Enter the number: "));
for (let i = 0; i <= n; i++) {
  sum += i; 
}
alert ("Sum of Numbers: " + 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