Java Program to Find Sum of Array Elements
for loop and adding each element to a sum variable, like int sum = 0; for(int num : array) sum += num;.Examples
How to Think About It
Algorithm
Code
public class SumArray { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int num : numbers) { sum += num; } System.out.println("Sum of array elements: " + sum); } }
Dry Run
Let's trace the array [1, 2, 3, 4, 5] through the code
Initialize sum
sum = 0
Add first element
sum = 0 + 1 = 1
Add second element
sum = 1 + 2 = 3
Add third element
sum = 3 + 3 = 6
Add fourth element
sum = 6 + 4 = 10
Add fifth element
sum = 10 + 5 = 15
Print result
Output: Sum of array elements: 15
| Iteration | Current Element | Sum After Addition |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
Why This Works
Step 1: Initialize sum
We start with sum = 0 because adding zero does not change the total.
Step 2: Loop through array
The for loop goes through each element one by one to access all numbers.
Step 3: Add elements to sum
Each element is added to sum using sum += num, updating the total.
Step 4: Print the result
After the loop, the final sum holds the total of all elements and is printed.
Alternative Approaches
public class SumArray { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; } System.out.println("Sum of array elements: " + sum); } }
import java.util.Arrays; public class SumArray { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int sum = Arrays.stream(numbers).sum(); System.out.println("Sum of array elements: " + sum); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each element once, so the time grows linearly with the array size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1), constant space.
Which Approach is Fastest?
All approaches run in O(n) time; using streams may have slight overhead but is concise. The for-each loop is simple and efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For-each loop | O(n) | O(1) | Simple and readable code |
| Traditional for loop | O(n) | O(1) | When index needed |
| Java Streams | O(n) | O(1) | Concise modern code |
for-each loop to keep your code simple and readable when summing array elements.