In this article, we are going to calculate the sum of n natural numbers using Java code.
Example
The sum of n natural numbers is calculated by using the formula n*(n+1)/2.
let assume n=10
n*(n+1)/2 = 10*(10+1)/2 = 10*(11)/2 = 110/2 = 55
Steps to calculate sum of n natural numbers
- Take input from the user.
- if n is negative or 0 then the result will be 0.
- if n is greater than 0 then calculate the sum of n number by using the formula.
- Print the result.
Java Code for Calculating Sum of n Natural Numbers
import java.util.Scanner;
public class SumOfNaturalNo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int n=sc.nextInt();
if(n>0) {
int sum = n*(n+1)/2;
System.out.println(sum);}
else {
System.out.println(0);
}
}}
We can use the same logic of calculating the sum of n natural numbers in other programming languages like C, C++, Java, etc.