Here’s a simple Java program that calculates and prints the sum of all elements in an array:
public class ArraySum {
public static void main(String[] args) {
// Initialize an array with some values
int[] array = {1, 2, 3, 4, 5};
// Variable to store the sum
int sum = 0;
// Loop through each element of the array and add it to the sum
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
// Print the sum of the array
System.out.println("Sum of all elements in the array: " + sum);
}
}
Explanation:
- Array Initialization:
- We define an array
array
with integers{1, 2, 3, 4, 5}
.
- We define an array
- Sum Calculation:
- We initialize a variable
sum
to store the total sum of array elements. - We loop through the array using a
for
loop, and for each iteration, we add the current element (array[i]
) tosum
.
- We initialize a variable
- Output:
- After the loop completes, we print the value of
sum
, which holds the total sum of the array elements.
- After the loop completes, we print the value of
Sample Output:
Sum of all elements in the array: 15
Alternative Using Enhanced For Loop (Java 5 and above):
You can also use the enhanced for
loop (also known as the “for-each” loop) for more concise code:
public class ArraySum {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int sum = 0;
// Enhanced for loop (for-each loop)
for (int num : array) {
sum += num;
}
System.out.println("Sum of all elements in the array: " + sum);
}
}
This version does the same thing but is more compact and readable. The enhanced for
loop iterates directly over the elements in the array without using an index.
Sample Output for Enhanced Loop Version:
Sum of all elements in the array: 15
Both approaches will give the same result, and you can use whichever one suits your coding style.