Advertisement
Home Data Structure Arrays Sum of Even Elements in an Array

Sum of Even Elements in an Array

0
Advertisement

Title: Sum of Even Elements in an Array

Adding up the even numbers in an array is one of the first filtering problems you meet when you start working with arrays in Java. It looks simple, yet it quietly touches a few important ideas: the modulus operator, how negative numbers behave under %, and how to accumulate a running total without introducing overflow. In this guide, you’ll learn a clear step-by-step approach, see a full Java program, walk through a dry run, and finish with the common traps and interview follow-ups you should be ready for.

Understanding the Problem

You are given an integer array, and your job is to return the sum of all elements that are divisible by two. The input may be empty, may contain only odd numbers, may contain negative numbers, and may contain zero. Zero is an even number, so if it appears in the array it contributes zero to the sum but should still be classified correctly. For an input like {3, 8, 2, 7, 10, 5, 4}, the even elements are 8, 2, 10, and 4, and the expected output is 24.

Approach

The idea is a single linear pass with one accumulator. We keep a running total, inspect each element, and add it to the total only when the element is even. The check num % 2 == 0 works for both positive and negative numbers in Java because the sign of the result of % follows the dividend, so -4 % 2 is still 0.

  1. Initialize a variable sum to 0.
  2. Iterate through every element num in the array using an enhanced for loop.
  3. For each num, test whether num % 2 == 0.
  4. If the test passes, add num to sum.
  5. After the loop ends, return sum as the final result.

Java Program

The following program defines a reusable sumOfEven method and a main that drives it with a sample input.

Java
public class SumOfEvenElements {

    public static int sumOfEven(int[] numbers) {
        int sum = 0;
        for (int num : numbers) {
            if (num % 2 == 0) {
                sum += num;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] numbers = {3, 8, 2, 7, 10, 5, 4};
        int result = sumOfEven(numbers);
        System.out.println("Sum of even elements: " + result);
    }
}

Explanation of the Program

The method sumOfEven takes an int[] and returns an int. Inside, we declare a local accumulator sum initialized to 0, which represents the running total of even values seen so far. The enhanced for loop walks each element without needing an index variable, which keeps the body focused on the decision we care about.

The guard if (num % 2 == 0) is the only branching logic. When it is true, we execute sum += num, which is shorthand for sum = sum + num. When it is false, the loop body does nothing and we move on. After the loop ends, return sum hands the final value back to the caller, and main prints it with System.out.println.

Step-by-Step Trace

Let us trace the method on the fresh input {1, 6, 3, 8, 2}, where the expected final sum is 16.

Iterationnumsum (before)num % 2 == 0?sum (after)
110no0
260yes6
336no6
486yes14
5214yes16

At the end of iteration i, sum holds the total of every even value seen in numbers[0..i]. That invariant is what makes a single linear pass sufficient: nothing has to be revisited.

Examples

Example 1: Every element is even

Java
int[] arr = {2, 4, 6, 8, 10};
// Sum of even elements: 30

Every value passes the % 2 == 0 test, so each one is added. The final total is 2 + 4 + 6 + 8 + 10 = 30.

Example 2: No element is even

Java
int[] arr = {1, 3, 5, 7, 9};
// Sum of even elements: 0

The if body never runs, so sum stays at its initial value of 0. The method still returns a well-defined result, which is why initializing sum to 0 matters.

Example 3: Negative evens and a zero

Java
int[] arr = {-6, 3, 0, 7, 4};
// Sum of even elements: -2

This case covers three pitfalls at once: a negative even value -6, the number 0 which is even, and a positive even 4. The sum is -6 + 0 + 4 = -2, which demonstrates that the result of this problem can legitimately be negative.

Common Mistakes to Avoid

These are the slip-ups that most often turn a correct-looking solution into a subtly wrong one.

  • Initializing sum to 1 – the result is off by one on every input, including the empty array. Initialize sum = 0 because adding to zero preserves the running total.
  • Using num % 2 != 0 to test for even – the condition is inverted and the method silently returns the sum of odd elements. Keep the test as num % 2 == 0.
  • Writing num & 1 == 0 without parentheses – because == binds tighter than & in Java, this parses as num & (1 == 0) and will not compile. Write (num & 1) == 0 if you prefer the bitwise form.
  • Accumulating into an int for a very large array – the running total silently overflows past Integer.MAX_VALUE and wraps to a negative number. Change sum to long when the input size or magnitude can be large.
  • Confusing sum with count – returning the number of even elements instead of their total. Make sure the body is sum += num, not sum++.

Edge Cases to Test

Before you call the method done, walk through this short list of inputs.

  • Empty array
  • Single even element
  • Single odd element
  • All even elements
  • All odd elements
  • Mix of positive and negative evens
  • Zero present in the array
  • Values near Integer.MAX_VALUE that force overflow risk
  • Null array reference

Additional Considerations

The time complexity is O(n) because every element is inspected exactly once and the work per element is constant. The space complexity is O(1) because the only extra storage is the accumulator and the loop variable, both independent of the array size.

Two Java-specific details are worth remembering. First, -4 % 2 is 0 in Java, so negative even values are classified correctly. Second, if the input could sum to a value outside the int range, promote the accumulator to long and change the return type accordingly, otherwise overflow will silently corrupt the answer.

Interview Follow-up Questions

Expect the interviewer to push on these variations once the base solution is working.

  • What if you need the sum of even elements only at even indices? – switch to an indexed for loop and add the inner condition i % 2 == 0 && numbers[i] % 2 == 0.
  • What if the input arrives as a stream of unknown length? – keep a running long accumulator and update it on each element until end-of-stream, with no need to buffer the input.
  • What if you must compute the sum, the count, and the maximum of even elements in a single pass? – maintain three accumulators that are updated inside the same if block so the array is scanned only once.
  • What if the array has billions of elements and does not fit in memory? – partition the input, sum each chunk independently, and combine the partial sums, which is a map-reduce friendly pattern.
  • Can you solve it with the Java Streams API? – use IntStream.of(numbers).filter(n -> n % 2 == 0).sum(), which is more declarative but still linear in time.

Conclusion

Summing the even elements of an array is a tidy single-pass problem that rewards clean initialization, a precise parity check, and awareness of overflow. Once you are comfortable with this template, the same shape generalizes to many other filtering-and-aggregating tasks, from summing values above a threshold to counting matches of any predicate you can state in one line.

Try adapting the code to return the sum of odd elements, the sum of elements divisible by three, or the average of the even values. You can learn more about array problems and interview-style solutions here: Arrays.