Java – Find Sum of First N Natural Numbers
To find the sum of first N natural numbers, you can either use direct formula or use a looping technique to traverse from 1 to to N and compute the sum.
sum = 1 + 2 + 3 + . . + n
In this tutorial, we shall start with Java programs using looping statements to compute the sum. Then we shall go through a Java program that uses formula to find the sum. At last, we shall look into recursion technique to find the sum.
Algorithm
Following algorithm can be used to find the sum of first N natural numbers using Java looping statements.
- Start.
- Read
n
. - Initialize
sum
with0
. - Initialize
i
with0
. - Check if
i
is less than or equal ton
. If false go to step 8. - Add
i
tosum
. - Increment
i
. Go to step 5. - Print the
sum
. - Stop.
Find Sum of First N Natural Numbers using While Loop
In the following Java program, we use Java While Loop to implement the algorithm to find sum of first N natural numbers.
Example.java
/**
* Java Program - Sum of First N Natural Numbers
*/
public class Example {
public static void main(String[] args) {
int n = 10;
int sum=0;
int i=1;
while (i<=n) {
sum += i;
i++;
}
System.out.println(sum);
}
}
Output
55
Find Sum of First N Natural Numbers using For Loop
In the following Java program, we use Java For Loop to implement the algorithm to find sum of first N natural numbers.
Example.java
/**
* Java Program - Sum of First N Natural Numbers
*/
public class Example {
public static void main(String[] args) {
int n = 10;
int sum=0;
for(int i=1; i<=n; i++)
sum += i;
System.out.println(sum);
}
}
Output
55
Find Sum of First N Natural Numbers using Formula
Formula to find the sum of first n Natural Numbers is n*(n+1)/2
. In the following Java program, we shall use this formula.
Example.java
/**
* Java Program - Sum of First N Natural Numbers
*/
public class Example {
public static void main(String[] args) {
int n = 10;
int sum = (n * (n + 1)) / 2;
System.out.println(sum);
}
}
Output
55
Find Sum of First N Natural Numbers using Recursion
We can also use recursion function to find the sum of first N natural numbers.
Example.java
/**
* Java Program - Sum of First N Natural Numbers
*/
public class Example {
public static void main(String[] args) {
int n = 10;
int sum = sumOfN(n);
System.out.println(sum);
}
static int sumOfN(int n) {
if (n == 1)
return 1;
else
return n + sumOfN(n-1);
}
}
Output
55
Conclusion
In this Java Tutorial, we learned how to compute the sum of first n natural numbers with the help of different techniques in Java.