public class SumArrayElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int n = arr.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
System.out.println("The sum of the array is: " + sum);
}
}
The sum of the array is: 28
arr
and initialize it with the example values {1, 2, 3, 4, 5, 6, 7}
. We get the length of the array n and declare an integer variable sum to store the sum
of all the elements in the array.for
loop to iterate through the array and add each element to the sum
variable. Finally, we print the sum of the array to the console using System.out.println()
.