Sum of elements in an array in Java with Logic and code example.
Consider an integer array as an example,
int[] x = { 6, 7, 2 }; //Sum of all elements of the array is 15.
LOGIC:
Simply retrieve each elements of the integer array by traversing the array using a for loop till the last elements. And in the loop, itself, during retrieval of each element keep adding them.
CODE EXAMPLE:
public class ArraySum {
public static void main(String[] args) {
int x[] = { 6, 7, 2 };
int sum = 0;
/* Retrieve each elements and keep summing. */
for (int i = 0; i < x.length; i++) {
sum += x[i];
// Also can be written as sum = sum + x[i];
}
System.out.println("sum=" + sum);
}
}
OUTPUT
Sum=15
TEST CASES
int x[] = { 6, -7, 2 };
Sum=1
int x[] = { -6, -7, -2 };
Sum=-15
MODULAR CODE – SUM OF ARRAY ELEMENTS IN JAVA
To modularize the program, you can create a separate method that takes an integer array, find sum of array elements and return the sum of the numbers of the array to the calling point.
CODE:
// Java program to find sum of array elements
public class ArraySum {
public static void main(String[] args) {
int x[] = { 6, 7, 2 };
int sum = getSum(x);
System.out.println("sum=" + sum);
}
public static int getSum(int arr[]) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
}