PUBLISHED ON: MARCH 15, 2023
JavaScript Program to Find the Sum of Natural Numbers
JavaScript is a programming language that is commonly used on websites to add interactivity and other dynamic features. It can also be used for server-side programming with tools like Node.js. We will use JavaScript in this program to calculate the sum of natural numbers up to a certain limit.
Natural numbers are positive integers beginning with one, such as one, two, three, four, and so on. The program will take an input limit and iterate through the natural numbers up to that limit, adding them all together to get the final sum. The sum will then be displayed to the user. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Approach:
We take the input from the user as shown in the below code.
The for Loop is used to find the sum of natural numbers up to the number provided by the user.
- We initialize the value of the global sum as 0.
- And then run a loop till the number interpreted by the user from 1.
- In each iteration, I is added to the sum till it reaches the number as the I is increased by +1 every time. As soon as I reach out of bounds (number), the loop stops running.
Program to Find the Sum of Natural Numbers Using For Loop
// JavaScript Program to display the Sum of Natural Numbers
const num = parseInt(prompt('Enter a positive integer: '));
let sum = 0;
for (var i = 1; i < num+1; i++)
sum += i;
console.log('The sum of Natural Numbers:' + sum);
Enter a positive integer: 10
The sum of Natural Numbers: 550
Conclusion
We used JavaScript in this program to calculate the sum of natural numbers up to a certain limit. The program starts with a limit and then iterates through the natural numbers up to that limit, adding them all up to get the final sum. The program then displays the end result to the user.
This program demonstrates how to use JavaScript to perform mathematical operations and use iteration.