Program to Find the Sum of First N Natural Numbers using java

sum of first n natural number in java

Find the Sum of first N natural Numbers

We know that Natural number is integer number which start from 1,2,3,4…… and so on.

So we will calculate the First N natural number

In the sum of first N natural number user gave the value of N. If the value is 6 then process is following

1+2+3+4+5+6 = 21

Implementation of  Sum of first N natural numbers

  • Step 1. Start
  • Step 2. Enter a number (N).
  • Step 3. Use formula to calculate the sum of N natural number || Sum=(n*(n+1))/2.
  • Step 4. Print sum of N Natural Number.
  • Step 5. Stop
Competitive Coding Techniques

Code of Sum of first N natural number in Java

//Java program to print the sum of n natural numbers
import java.util.Scanner;
public class sum_of_n_natural_numbers
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);

//input from user
System.out.print("Enter a number : ");
int n = sc.nextInt();
//declare a variable to store sum
int sum=(n*(n+1))/2;

//display the sum
System.out.print("Sum of n natural numbers is "+sum);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output

Enter a number : 5
Sum of n natural numbers is 15