Java Program to Calculate the Sum of Natural Numbers

In this program, you’ll learn to calculate the sum of natural numbers using for loop and while loop in Java.

The positive numbers 1, 2, 3… are known as natural numbers and its sum is the result of all numbers starting from 1 to the given number.

For n, the sum of natural numbers is:

1 + 2 + 3 + ... + n

Example 1: Sum of Natural Numbers using for loop

  1. public class SumNatural {
  2. public static void main(String[] args) {
  3. int num = 100, sum = 0;
  4. for(int i = 1; i <= num; ++i)
  5. {
  6. // sum = sum + i;
  7. sum += i;
  8. }
  9. System.out.println("Sum = " + sum);
  10. }
  11. }

When you run the program, the output will be:

Sum = 5050

The above program loops from 1 to the given num(100) and adds all numbers to the variable sum.


You can solve this problem using a while loop as follows:

Example 2: Sum of Natural Numbers using while loop

  1. public class SumNatural {
  2. public static void main(String[] args) {
  3. int num = 50, i = 1, sum = 0;
  4. while(i <= num)
  5. {
  6. sum += i;
  7. i++;
  8. }
  9. System.out.println("Sum = " + sum);
  10. }
  11. }

When you run the program, the output will be:

Sum = 1275

In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.

Though both programs are technically correct, it is better to use for loop in this case. It’s because the number of iteration (upto num) is known.

Visit this page to learn how to find the sum of natural number using recursion.