Java Program to calculate sum of First N Natural numbers

Get input n and calculate the sum of first n natural numbers.

Sample Input 1:

5

Sample Output 1:

The sum is: 15

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution

				
			
					
import java.util.*;
class SumOfN
  {
    public static void main(String args[])
    {
      int i,lim,sum=0;
      System.out.println("Enter The Limit:");
      Scanner sc=new Scanner(System.in);
      lim=sc.nextInt();
      for(i=1;i<=lim;i++)
      {
            sum=sum+i;
      }
      System.out.println("The Sum Is: "+sum);
    }
}
			
				
			

Program Explanation

1. Get input limit (upto which number natural numbers to be printed) 

2. Instruction(s) inside the for block{} are executed repeatedly till i less than or equal to limit.              (i<=limit)

    for(i=1;i<=lim;i++)

3. Here i is initialized to 1 and incremented by 1 for each iteration, instructions inside the for block      are executed in every iteration. Iteration stops when i becomes greater than limit.

so value of i will be added to the variable sum like

sum = sum + i

sum = 0 + 1

sum = 1 + 2

sum = 3 + 3

sum = 6 + 4

.......

.......

Finally the sum will be printed using println

Comments