Java Program to Calculate the Sum of Natural Numbers

In this java program, we will learn about how to calculate the sum of natural numbers using for loop and while loop.

The natural numbers are the numbers that include all integers from 1 to infinity. To find the sum of all natural number till N, we have to add all numbers between 1 to N.

The sum of natural numbers till N is:
1 + 2 + 3 + ... + N

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to find the sum of natural numbers using while loop

public class NumbersSumWhileLoop {
  public static void main(String[] args) {
    int num = 100, count = 1, totalSum = 0;

    while (count <= 100) {
      totalSum = totalSum + count;
      count++;
    }

    System.out.format("Sum of number from 1 to %d is %d",num,totalSum);
  }
}
Output
Sum of number from 1 to 100 is 5050

The above java program, we are using for while loop to iterate from 1 to 100 and adds all numbers to the variable totalSum. First, we initialze count with 1 and then in every iteration of while loop, we add the value of count to totalSum and then increment it. While loop will terminate when count becomes more than 100.


Program to calculate the sum of natural numbers using for loop

public class NumbersSumForLoop {
  public static void main(String[] args) {
    int num = 100, count, totalSum = 0;

    for(count = 1; count <= num; count++){
      totalSum = totalSum + count;
    }
    System.out.format("Sum of number from 1 to %d is %d", num, totalSum);
  }
}
Output
Sum of number from 1 to 100 is 5050

The above java program, we are using for loop to iterate from 1 to 100 and adds all numbers to the variable totalSum.