Advertisement
Home Data Structure Arrays Product of Even and Odd Elements in an Array

Product of Even and Odd Elements in an Array

0
Advertisement

Title: Product of Even and Odd Elements in an Array

In this guide, we will solve a classic beginner-friendly array problem in Java: computing the product of all even elements and the product of all odd elements in a given integer array. You will learn how to iterate through the array once, classify each element with the modulus operator, and accumulate two separate running products. We will also look at the trade-offs around overflow, empty-category handling, and the interview follow-ups you should expect once the base problem is done.

Understanding the Problem

Given an integer array numbers, we want two values: the product of every even element and the product of every odd element. An element is considered even when value % 2 == 0 and odd otherwise. For the input {2, 7, 4, 9, 6, 3, 8}, the even product is 2 * 4 * 6 * 8 = 384 and the odd product is 7 * 9 * 3 = 189.

The problem looks small, but it hides two decisions worth making consciously. First, what should we return when the array has no even elements (or no odd elements)? Returning 1 silently is misleading because 1 is the empty-product identity. Second, products grow quickly, so the accumulator type must be chosen with overflow in mind.

Approach

A single linear scan is enough. We maintain two long accumulators initialized to 1 and two boolean flags that record whether we actually saw an even or odd element. Here are the steps:

  1. Initialize evenProduct and oddProduct to 1 (the multiplicative identity).
  2. Initialize hasEven and hasOdd to false so we can distinguish the empty-category case from a legitimate product of 1.
  3. Iterate over every element of numbers with an enhanced for loop.
  4. If the element is divisible by 2, multiply it into evenProduct and set hasEven to true.
  5. Otherwise, multiply it into oddProduct and set hasOdd to true.
  6. After the loop, print each product only if its flag is set; otherwise print a clear message that no such element exists.

Java Program

The complete, compilable program is shown below. Save it as ProductEvenOddInArray.java, compile with javac, and run with java ProductEvenOddInArray.

Java
public class ProductEvenOddInArray {
    public static void main(String[] args) {
        int[] numbers = {2, 7, 4, 9, 6, 3, 8};
        long evenProduct = 1;
        long oddProduct = 1;
        boolean hasEven = false;
        boolean hasOdd = false;

        for (int value : numbers) {
            if (value % 2 == 0) {
                evenProduct = evenProduct * value;
                hasEven = true;
            } else {
                oddProduct = oddProduct * value;
                hasOdd = true;
            }
        }

        if (hasEven) {
            System.out.println("Product of even elements: " + evenProduct);
        } else {
            System.out.println("No even elements in the array.");
        }

        if (hasOdd) {
            System.out.println("Product of odd elements: " + oddProduct);
        } else {
            System.out.println("No odd elements in the array.");
        }
    }
}

Explanation of the Program

The two accumulators are declared as long rather than int because products balloon far faster than sums. An array of eight medium-sized int values can easily exceed the Integer.MAX_VALUE ceiling of about 2.1 billion. Using long buys roughly 9.2 quintillion of headroom, which is still finite but comfortably large for most real inputs.

The flags hasEven and hasOdd solve a subtle correctness problem. If every element happens to be odd, evenProduct would remain at 1, and a caller reading that value cannot tell “there were no even elements” apart from “the even elements multiplied to 1”. The flags make the empty-category case explicit at the print site.

The enhanced for loop over numbers keeps the body focused on the classification and the mutation. The condition value % 2 == 0 works for both positive and negative integers in Java because the sign of the remainder follows the dividend, so -4 % 2 is still 0 and -4 is correctly classified as even.

Step-by-Step Trace

Let us trace the algorithm on the input {5, 2, 8, 3, 1}. The expected result is an even product of 16 and an odd product of 15.

IterationvalueEven?evenProduct (before -> after)oddProduct (before -> after)
15no1 -> 11 -> 5
22yes1 -> 25 -> 5
38yes2 -> 165 -> 5
43no16 -> 165 -> 15
51no16 -> 1615 -> 15

At the end of iteration i, evenProduct holds the product of all even values in numbers[0..i] and oddProduct holds the product of all odd values in the same prefix. That invariant is what the loop maintains, and it is the pedagogical core of this algorithm.

Examples

Example 1: Mixed Positive Values

Java
// Input
int[] arr = {4, 7, 2, 9, 6};

// Output
Product of even elements: 48
Product of odd elements: 63

The even elements 4, 2, and 6 multiply to 48, and the odd elements 7 and 9 multiply to 63. Both flags are set, so both lines are printed.

Example 2: All Odd Elements

Java
// Input
int[] arr = {1, 3, 5, 7};

// Output
No even elements in the array.
Product of odd elements: 105

Because the even category is empty, hasEven stays false and the program prints the “no even elements” message instead of a misleading product of 1.

Example 3: All Even Elements

Java
// Input
int[] arr = {10, 10, 10};

// Output
Product of even elements: 1000
No odd elements in the array.

The three even elements multiply to 1000, and the odd category reports its absence cleanly through the hasOdd flag.

Common Mistakes to Avoid

A few traps catch learners again and again on this problem. Here are the ones worth internalizing before you ever run the code.

  • Initializing products to 0 – every multiplication collapses to 0, so you always print 0 regardless of the input. Initialize both accumulators to 1 because 1 is the multiplicative identity.
  • Letting a zero element poison the even product – a single 0 silently zeros evenProduct because 0 is even. Decide up front whether to skip zeros or document that the product is zero by design.
  • Forgetting that negatives can be even – treating -4 as odd because of the sign makes the classification wrong. Classify by value % 2 == 0, which handles negative integers correctly in Java.
  • Accumulating in int – products overflow silently and wrap into negative numbers for even medium arrays. Store the running products in long, or use BigInteger when overflow must be impossible.
  • Reporting 1 for the empty category – hides the “no such element” case behind a legitimate-looking value. Track a boolean flag per category and branch on it when you print.

Edge Cases to Test

Before calling this problem solved, make sure the following inputs behave exactly as documented.

  • Empty array
  • Single-element array
  • Array containing zero
  • All even elements
  • All odd elements
  • Array with negative numbers
  • Values large enough to overflow long
  • Null array reference

Additional Considerations

The algorithm runs in O(n) time because every element is inspected exactly once. The extra space is O(1): the two long products and the two boolean flags do not grow with the input. This is as efficient as the problem allows, since any correct answer must at least read every element of the array.

Overflow is the hidden complexity. Even with long, roughly 20 to 30 medium-magnitude elements can exceed Long.MAX_VALUE. If your input can realistically contain that many elements, switch to java.math.BigInteger and multiply with BigInteger.multiply, or take the product modulo a large prime when the problem permits.

A null array should fail fast with an IllegalArgumentException at the top of the method rather than throwing a NullPointerException deep inside the loop. Explicit guards make the method contract readable, and the stack trace points at the real caller instead of a random for-each line.

Interview Follow-up Questions

Interviewers rarely stop at the base problem. These variations show up most often, and each one changes something fundamental about the solution.

  • What if duplicates must count only once per category? – keep a HashSet<Integer> of the values already multiplied in and skip repeats before updating the running product.
  • What if the product must be returned modulo 10^9 + 7? – multiply, then take the modulus after each step so the accumulator never leaves long range; the loop body gains one extra operation and overflow disappears.
  • What if the array arrives as a stream of unknown length? – the algorithm is already single-pass, so update the two running products inside the stream consumer and finalize when the stream ends.
  • What if the input has billions of elements and does not fit in memory? – partition the input across workers, compute the two products per partition independently, then multiply the partition products together; the step is embarrassingly parallel.
  • What if you must do it without the boolean flags? – count the elements per category instead, then treat a count of zero as the “empty category” signal when printing.

Conclusion

Computing the product of even and odd elements is a compact exercise that bundles three real-world skills: iterating with a clean invariant, choosing a numeric type that respects overflow, and distinguishing an empty category from a product of 1. Keep the flags, keep the long, and the code reads as cleanly as the specification.

Adapt the program to your own exercises: try returning both products as a long[], switch to BigInteger for unbounded inputs, or extend it to compute the product of elements at even and odd indices instead of even and odd values. You can learn more about array problems in Java here: Arrays on Daily Java Concept.