Algorithm
-
Input:
- Prompt the user to enter a positive integer (n) representing the last natural number in the series.
-
Initialize Variables:
- Initialize a variable
sum
to store the sum and set it to 0.
- Initialize a variable
-
Loop:
- Use a loop to iterate from 1 to n (inclusive).
- In each iteration, add the current value of the loop variable to the
sum
.
-
Output:
- Print or display the value of
sum
as the result.
- Print or display the value of
Code Examples
#1 Code Example- Sum of Natural Numbers Using for Loop
Code -
Javascript Programming
// program to display the sum of natural numbers
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
let sum = 0;
// looping from i = 1 to number
// in each iteration, i is increased by 1
for (let i = 1; i < = number; i++) {
sum += i;
}
console.log('The sum of natural numbers:', sum);
Copy The Code &
Try With Live Editor
Output
Enter a positive integer: 100
The sum of natural numbers: 5050
The sum of natural numbers: 5050
#2 Code Example- Sum of Natural Numbers Using while Loop
Code -
Javascript Programming
// program to display the sum of natural numbers
// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));
let sum = 0, i = 1;
// looping from i = 1 to number
while(i < = number) {
sum += i;
i++;
}
console.log('The sum of natural numbers:', sum);
Copy The Code &
Try With Live Editor
Output
Enter a positive integer: 100
The sum of natural numbers: 5050
The sum of natural numbers: 5050
Demonstration
JavaScript Programing Example to Find the Sum of Natural Numbers-DevsEnv