Finding the sum of all elements in an array.
Here’s a simple Java program that calculates the sum of all elements in an array:
public class ArraySum { public static void main(String[] args) { int[] array = { 1, 2, 3, 4, 5 }; int sum = calculateSum(array); System.out.println("The sum of the array elements is: " + sum); } public static int calculateSum(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; } }
In this program, we define an array called `array` with some sample elements. The `calculateSum` method iterates through each element of the array, adding it to the `sum` variable. Finally, we print the sum using `System.out.println`.
No comments yet! You be the first to comment.