In this Java tutorial, you’ll learn how to Calculate the Sum of Natural Numbers using the Java programming language.
How to calculate the sum of natural numbers in JAVA?
Example 1: using for loop
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { int num = 50, sum = 0; for(int i = 1; i <= num; ++i) { sum += i; } System.out.println("Sum = " + sum); } }
OUTPUT
Sum = 1275
In the above program, the added value is stored in the variable sum. The loop adds the value from 1 to the given number 50.
Example 2: using while loop
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { int num = 5, i = 1, sum = 0; while(i <= num) { sum += i; i++; } System.out.println("Sum = " + sum); } }
OUTPUT
Sum = 15
In the above example, the while loop executes until the “i<=num” condition is true.