English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive List of Java Examples
In this program, you will learn how to use for loops and while loops in Java to calculate the sum of natural numbers.
positive numbers1,2,3 ...are called natural numbers, and their sum is from1The result of all digits up to the given number.
The sum of natural numbers for n is:
1 + 2 + 3 + ... + n
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); } }
When running the program, the output is:
Sum = 5050
The above program starts from1to the given num(10Add all numbers to the variable sum in a 0) loop.
You can solve this problem using a while loop as shown below:
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); } }
When running the program, the output is:
Sum = 1275
In the above program, unlike the for loop, we must increase the value of i within the loop body.
Although both programs are technically correct, it is best to use a for loop in this case. This is because the number of iterations (up to num) is known.