Program for Sum of N natural numbers using Java

Sum of N natural numbers using java :

 

In this article we will perform addition on first n natural numbers, where n is a number upto which we have to perform addition. So we create a java program to print the sum of n natural numbers.

 

For better understanding let’s suppose the value of n is 5 then,

Sum of first 5 natural numbers will be (1+2+3+4+5) = 15.

 

So we create a java program to calculate sum of first n natural numbers.

Sum of N natural numbers using java

Working :

Step 1 : Ask the user to enter a  number which will denote the limit.

Step 2 : Declare a variable to store the addition and initialize it with 0.

Step 3 : Use a loop to perform iterations for adding natural numbers from 1 till the limit entered by the user.

Step 4 : Use a statement for addition purpose.

Step 5 : Print the result.

Code 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=0;
//loop to add n natural numbers
for(int i = 1 ; i <= n ; i++)
sum=sum+i;
//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 : 15

Sum of n natural numbers is 120


Enter a number : 5

Sum of n natural numbers is 15