Sum of n numbers in java

Java program for sum of first N number. If value of N is 10 then program will print sum as 55.

import java.util.Scanner;
public class Main
{

 public static void main(String[] args)
 {
  int sum=0,N;
  Scanner input=new Scanner(System.in);
  System.out.println("enter N value:");
  N=input.nextInt();
  System.out.println("entered value is:"+ N);
  input.close();
		
  for (int i=1;i<=N;i++)
  {
    sum=sum+i;
  }
  System.out.println("Sum of N number is "+sum);
	
 }
}
OUTPUT:
enter N value:
10
entered value of N is:10
Sum of N number is 55

Another Way for sum of first N number:

import java.util.Scanner;
public class Main
{

 public static void main(String[] args)
 {
  int sum=0,N;
  Scanner input=new Scanner(System.in);
  System.out.println("enter N value:");
  N=input.nextInt();
  System.out.println("entered value is:"+ N);
  input.close();
  sum=(N*(N+1))/2;
  System.out.println("Sum of N number is "+sum);
	
 }
}
enter N value:
10
entered value is:10
Sum of N number is 55

Leave a Reply