Java Code to print the sum of all the items of an array

In this program, our task is to calculate the sum of all the elements in an array. To achieve this, we can use a loop to iterate through each element of the array. In each iteration, we add the value of the current element to a variable called “sum.”

The sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

Algorithm for a Java Code to print the sum of all the items of an array

STEP 1: START
STEP 2: Initialize the array arr[] with values {1, 2, 3, 4, 5}
STEP 3: Set the variable sum to 0
STEP 4: Repeat steps 5 to 7 until i is less than the length of arr[]
// for(i=0; i<arr.length; i++)
STEP 5: Add the value of arr[i] to the sum variable: sum = sum + arr[i]
STEP 6: Print the message “Sum of all the elements of the array:”
STEP 7: Print the value of the sum
STEP 8: END

Java Code to print the sum of all the items of an array

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

In conclusion, the provided Java code is designed to calculate and print the sum of all the elements in an array. It achieves this by initializing a variable, sum, to zero and utilizing a loop to iterate through each element of the array. Within each iteration, the value of the current element is added to the sum variable. By repeating this process for all elements, the sum variable accumulates the total sum of the array elements. Follow tutorials.freshersnow.com to learn more.