How to Find the Sum of Even and Odd Elements Separately in an Array
Finding the sum of even and odd elements separately combines two fundamental programming concepts: checking whether a number is even or odd and maintaining running totals. By using two accumulator variables, you can calculate both sums in a single traversal of the array, making the solution both simple and efficient.
Problem Statement
Given an array like:
{10, 15, 22, 7, 8, 3}
Calculate:
- Sum of even elements:
10 + 22 + 8 = 40 - Sum of odd elements:
15 + 7 + 3 = 25
Method 1: Single Loop With Dual Accumulators (Recommended)
public class SumEvenOddSeparately {
public static void main(String[] args) {
int[] numbers = {10, 15, 22, 7, 8, 3};
int evenSum = 0;
int oddSum = 0;
for (int num : numbers) {
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
}
System.out.println("Sum of even elements: " + evenSum);
System.out.println("Sum of odd elements: " + oddSum);
}
}
This is the most efficient approach because both sums are calculated during a single pass through the array.
Method 2: Java Streams
import java.util.Arrays;
int evenSum = Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.sum();
int oddSum = Arrays.stream(numbers)
.filter(n -> n % 2 != 0)
.sum();
This solution is concise and easy to read, but it traverses the array twice—once to calculate the even sum and once to calculate the odd sum.
Step-by-Step Explanation
Initialize Two Accumulators
Create two variables:
evenSumfor storing the sum of even numbers.oddSumfor storing the sum of odd numbers.
Both variables are initialized to zero.
Process Each Element
Traverse the array one element at a time.
If the current number is even (num % 2 == 0), add it to evenSum.
Otherwise, add it to oddSum.
Since a number cannot be both even and odd, only one accumulator is updated during each iteration.
Final Result
After the loop completes, evenSum contains the total of all even numbers, while oddSum contains the total of all odd numbers.
Internal Working (Memory View)
For the array:
numbers = [10, 15, 22, 7, 8, 3]
Processing:
10 -> Even
evenSum = 10
15 -> Odd
oddSum = 15
22 -> Even
evenSum = 32
7 -> Odd
oddSum = 22
8 -> Even
evenSum = 40
3 -> Odd
oddSum = 25
Final result:
evenSum = 40
oddSum = 25
Real-Life Analogy
Imagine two donation boxes at an event.
One box collects donations from morning attendees, while the other collects donations from afternoon attendees.
Each donation is placed into the appropriate box as it arrives. By the end of the event, each box already contains the correct total without needing to sort the donations afterward.
Best Practices
- Use a single loop with two accumulator variables for maximum efficiency.
- Initialize both accumulator variables to zero before processing the array.
- Use
longinstead ofintif the array may contain very large values or many elements. - Consider returning both sums together if this logic is reused frequently.
Common Mistakes
- Using two separate loops instead of a single traversal.
- Forgetting to initialize the accumulator variables.
- Using
intwhen the total may exceed the integer range. - Confusing the sum of even elements with the sum of elements at even indices.
Expert Tips
- The dual-accumulator pattern is useful for many similar problems, such as calculating separate counts and sums simultaneously.
- When working with negative numbers, always check
num % 2 == 0for even numbers and use theelsebranch for odd numbers instead ofnum % 2 == 1. - If additional statistics such as count, minimum, maximum, or average are needed, maintain extra accumulator variables during the same traversal.
Comparison Table
| Method | Passes Through Array | Efficiency | Readability |
|---|---|---|---|
| Single Loop With Dual Accumulators | 1 | Excellent | High |
Java Streams (filter().sum()) |
2 | Good | Very High |
Frequently Asked Questions
Can I calculate both sums in one loop?
Yes. Using two accumulator variables allows both sums to be calculated during a single traversal of the array.
Do I need two separate stream operations?
No. A single loop is more efficient. Streams use separate filter-and-sum operations, making the array traversal occur twice.
Does this work with negative numbers?
Yes. The parity check num % 2 == 0 correctly identifies even numbers regardless of whether they are positive or negative.
Should I use long instead of int?
If the array contains very large numbers or many elements, using long helps prevent integer overflow.
How is this different from counting even and odd elements?
Counting determines how many numbers belong to each category, while this problem calculates the total value of each category.
Can I calculate the average of even and odd elements?
Yes. Track both the sum and the count for each category, then divide the sum by the corresponding count using double arithmetic.
Can this approach be used for a 2D array?
Yes. Use nested loops to visit every element while maintaining the same two accumulator variables.
What is the time complexity?
The single-loop solution has a time complexity of O(n) because each element is processed exactly once.