Algorithm


  1. Input:

    • Prompt the user to enter a positive integer (n) representing the last natural number in the series.
  2. Initialize Variables:

    • Initialize a variable sum to store the sum and set it to 0.
  3. 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.
  4. Output:

    • Print or display the value of sum as the result.

 

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

x
+
cmd
Enter a positive integer: 100
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

x
+
cmd
Enter a positive integer: 100
The sum of natural numbers: 5050
Advertisements

Demonstration


JavaScript Programing Example to Find the Sum of Natural Numbers-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way