Sum of n Natural Numbers

Program to calculate sum of first n natural numbers

BeginnerTopic: Loop Programs
Back

JavaScript Sum of n Natural Numbers Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Using for loop
let n = 10;
let sum = 0;

for (let i = 1; i <= n; i++) {
    sum += i;
}

console.log("Sum of first", n, "natural numbers:", sum);

// Method 2: Using formula (n × (n + 1)) / 2
let num = 10;
let sumFormula = (num * (num + 1)) / 2;
console.log("Using formula:", sumFormula);

// Method 3: Using while loop
let number = 10;
let total = 0;
let counter = 1;

while (counter <= number) {
    total += counter;
    counter++;
}

console.log("Using while loop:", total);

// Method 4: Using function
function sumNaturalNumbers(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

console.log("Using function:", sumNaturalNumbers(10));

// Method 5: Using reduce (functional approach)
function sumNaturalNumbersReduce(n) {
    return Array.from({length: n}, (_, i) => i + 1)
                 .reduce((sum, num) => sum + num, 0);
}

console.log("Using reduce:", sumNaturalNumbersReduce(10));
Output
Sum of first 10 natural numbers: 55
Using formula: 55
Using while loop: 55
Using function: 55
Using reduce: 55

Understanding Sum of n Natural Numbers

This program demonstrates different approaches to calculate sum of natural numbers.

Natural Numbers

Positive integers: 1, 2, 3, 4, 5, ...

Method 1: For Loop

Iterative approach:

let sum = 0;
for (let i = 1; i <= n; i++) {
    sum += i;
}

Compound Assignment

sum += i is shorthand for sum = sum + i

+=: Addition assignment
-=: Subtraction assignment
*=: Multiplication assignment
/=: Division assignment

Method 2: Mathematical Formula

Gauss's formula: n × (n + 1) / 2
let sum = (n * (n + 1)) / 2;

Pros:

O(1) time complexity
No loop needed
Most efficient

Example:

Sum of 1 to 10 = (10 × 11) / 2 = 55

Method 3: While Loop

Condition-based iteration:

while (counter <= number) {
    total += counter;
    counter++;
}

Method 4: Function

Reusable code:

function sumNaturalNumbers(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += i;
    }
}
    return sum;

Method 5: Functional Approach (ES6)

Using array methods:

Array.from({length: n}, (_, i) => i + 1)
     .reduce((sum, num) => sum + num, 0);

Array.from()

: Creates array from iterable

reduce()

: Accumulates values

Time Complexity:

Loop methods: O(n)
Formula: O(1) - Best!

When to Use:

-

Formula

: Best performance

-

Loop

: Learning, flexible logic

-

Reduce

: Functional programming style

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Sum of n Natural Numbers

This JavaScript program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents