Java Program to Calculate the Sum of Natural Numbers

Example 1: Sum of Natural Numbers using for loop

public class SumNatural {

    public static void main(String[] args) {

        int num = 100, sum = 0;

        for(int i = 1; i <= num; ++i)
        {
            // sum = sum + i;
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

Output

Sum = 5050

Example 2: Sum of Natural Numbers using while loop

public class SumNatural {

    public static void main(String[] args) {

        int num = 50, i = 1, sum = 0;

        while(i <= num)
        {
            sum += i;
            i++;
        }

        System.out.println("Sum = " + sum);
    }
}

Output

Sum = 1275

Leave a Reply