Sum of array elements in Java

 


In this program we are going to sum the elements in the array list using the java programming.

  In this program we are getting the input from the user.The first input is number of elements that can be stored at the array. 

  After getting n the for loop will get execute.The n elements will be stored at the array.

  Again the for loop will be executed then sum of the array elements process will done.

Program:

package p;
import java.util.*;
public class demo {

  public static void main(String[] args) {
   Scanner sc=new Scanner(System.in);
  int n;
  System.out.println("Enter the number of integers");
  n=sc.nextInt();
  int a[]=new int[n];
  int sum=0;
  for(int i=0;i<n;i++)
  {
   a[i]=sc.nextInt();
     }
  for(int i=0;i<n;i++)
  {
   sum+=a[i];
  }
  System.out.println("Sum of integers : "+sum);
  }
  }

Output:

Enter the number of integers
5
1
2
3
4
5
Sum of integers : 15




0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post