It is the Basic Java Program to find the sum of N natural numbers. The program below uses the While loop, if you want to learn about the while loop click below.
Example: If you want to find the sum of 5 natural numbers, the process will be executed in this manner:1 + 2 + 3 + 4 + 5
The result will be: 15
Java Program to Find the Sum of Natural Numbers using While Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //Sum of Natural numbers in java public class SumNaturalNumbers { public static void main(String[] args) { int n = 100, count = 1, sum = 0; while(count <= n) { sum = sum + count; count++; } System.out.println("Sum: "+sum); } } |
Output:
Sum: 5050
In the above program, n is already defined in the program but if you wish to take the input of n from the user, just use the scanner class.