OneBite.Dev - Coding blog in a bite size

find the sum of all elements in an array in java

Code snippet on how to find the sum of all elements in an array in java

int sum = 0;
int[] array = {1,2,3,4,5};
 
for (int i=0; i < array.length; i++) {
  sum = sum + array[i];
}
 
System.out.println("Sum of array values is: " + sum);

This code uses a loop to iterate through an array of integers called “array” and keep a running total of the sum in the “sum” integer. The first line outside the loop sets the sum to 0 initially. The loop starts at 0 (the first element in an array is always at the 0th index) and runs until it reaches the length of the array. Inside the loop, the current value of the array is added to the sum, and the loop continues until the end of the array is reached. Finally, the value of sum is output to the console.

java