Sum of elements of array program

simple java program to sum all the numbers in an integer array. Build-in function to sum a values in array is used in java8. array_sum in php.

class Sumarray{
    public static void main(String args[])  {
int[] a={8,5,6,2,4};
int sum=0;
for(int i=0;i<  a.length;i++)
{
sum +=a[i];
}
System.out.println(“Sum of array”+sum);
}}

 

output:
Sum of array 25

Explanation:
At begining the  value of variable “sum”  will be 0.
sum +=a[i] is the short form of sum = sum+a[i] can be used either.
All the element of array will be iterated and added to the variable “ sum”.

Build in method to sum the numbers in array - JAVA8
stream is used in java8.. java8 documentation

 

int[] sarray = {10,20,30,40,50};
int sum = IntStream.of(sarray).sum();
System.out.println("The sum is " + sum);