Unlock the Power of Java Loops: Calculating the Sum of Natural Numbers

What are Natural Numbers?

Natural numbers, also known as positive integers, are a series of numbers starting from 1 and going up to infinity. The sum of these numbers is the result of adding all numbers from 1 to a given number. For instance, if we want to find the sum of natural numbers up to 100, we’ll add 1 + 2 + 3 +… + 100.

Using a For Loop to Calculate the Sum

One way to calculate the sum of natural numbers is by using a for loop. Here’s an example:


public class Main {
    public static void main(String[] args) {
        int num = 100;
        int sum = 0;
        for (int i = 1; i <= num; i++) {
            sum += i;
        }
        System.out.println("The sum of natural numbers up to " + num + " is " + sum);
    }
}

This program loops from 1 to the given number (in this case, 100) and adds each number to the sum variable. The result is then printed to the console.

Alternative Approach: Using a While Loop

While a for loop is a great way to solve this problem, we can also use a while loop. Here’s the equivalent code:


public class Main {
    public static void main(String[] args) {
        int num = 100;
        int sum = 0;
        int i = 1;
        while (i <= num) {
            sum += i;
            i++;
        }
        System.out.println("The sum of natural numbers up to " + num + " is " + sum);
    }
}

In this example, we need to increment the value of i inside the loop body. Although both programs produce the correct result, the for loop is generally preferred when the number of iterations is known.

Recursion: Another Way to Calculate the Sum

Did you know that you can also calculate the sum of natural numbers using recursion? Learn more about it!

Leave a Reply