Table of Contents
In this program, you will learn how to use the for loop and while loop in Java to calculate the sum of natural numbers. To understand this example, you need to be familiar with the following Java programming concepts:
- Java for Loop
- Java while and do…while Loop
Positive numbers such as 1, 2, 3… are known as natural numbers, and their sum is the result of all numbers beginning with 1 and ending with the given number.
For n, the sum of natural numbers is:
1 + 2 + 3 + ... + n
Learn Coding in your Language! Enroll Here!
Sum of Natural Numbers using for loop
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);
}
}
Output
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:
Sum of Natural Numbers using while loop
1: What is the default value of a boolean in Java?
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);
}
}
Output
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 (up to num) is known.