Java Program to Find The Sum of elements in an array

In this post we will be going to learn all the Java program to find the sum of elements in an array . I will discussing all the ways to find the sum of elements in array using Java.

Let’s see using an example, Consider a given array : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] , then the sum of all elements in this array will be

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Now, let’s see all the following way to find the sum of elements in a given array using Java

Basic Java Loop

We can find the sum of elements in a given array using Loops in Java.

Algorithm

Java program to find the sum of elements in an array using basic for loop

  • Step 1: START
  • Step 2: Initialize Array arr[]
  • Step 3: Declare sum = 0
  • Step 4: Repeat step 5 until i<arr.length
  • Step 5: sum = sum + arr[i]
  • Step 6: Print “Sum of all elements in array :”
  • Step 7: Print sum
  • Step 8: END

1. Using For Loop

We can find sum of all the elements in the array using for loop. Now, let’s see the code,

Code

    public class SumOfArray {  
        public static void main(String[] args) {  
            //Initialize array  
            int [] arr = new int [] {1, 2, 3, 4, 5};  
            int sum = 0;  
            //Loop through the array to calculate sum of elements  
            for (int i = 0; i < arr.length; i++) {  
               sum = sum + arr[i];  
            }  
            System.out.println("Sum of all the elements of an array: " + sum);  
        }  
    }  

Output

  Sum of all the elements of an array: 15

2. Using For-Each Loop

Now let’s see how to find the sum of all elements using For-each loop in Java

Code

  class SumOfArray{
   public static void main(String args[]){
      int[] array = {10, 20, 30, 40, 50};
      int sum = 0;
      //Advanced for loop
       for( int num : array) {
          sum = sum+num;
       }
       System.out.println("Sum of array elements is:"+sum);
    }
 }

Output

  Sum of all the elements of an array: 150

Using Java Stream (inbuilt function in Java)

We can also find sum of all the elements of array in Java using Java Stream’s inbuilt sum() function

Java program to find the sum of elements in an array using Java Stream API

Code

  class SumOfArray{
     public static void main(String args[]){
        int[] array = {10, 20, 30, 40, 50};
        //Using Java Stream API
        int sum = Arrays.stream(array).sum();
 
        System.out.println("Sum of array elements is:"+sum);
     }
  } 

Output

  Sum of all the elements of an array: 150

Conclusion

Today, you learn all Java programs to find sum of elements in an array by using basic for loops, using advance for-each loop and by using Java Stream API inbuilt sum() function.

Thanks for learning from codingbroz to learn more about Java or programming , read our other posts too !

Broz Who Code

CodingBroz

Leave a Comment

Your email address will not be published. Required fields are marked *