In this example, you’ll learn how to calculate the sum of natural numbers using for loop.
Java Code: Write a java program to calculate the sum of natural numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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: