Placement Prep

Count Even and Odd Elements in an Array

Single-pass O(n) algorithm to count even and odd elements in an array. Working code in C, C++, Python, and Java, with complexity analysis and edge cases.

By FACE Prep Team 4 min read
arrays even-odd data-structures placement-prep algorithms c-programming python coding-interview

Counting even and odd elements in an array is a single-pass problem: initialize two counters to zero, scan every element once, and apply the modulo-2 rule to decide which counter to increment.

Problem Statement and Expected Output

Given an integer array of size n, count how many elements are even and how many are odd, then print both totals.

An integer is even when dividing it by 2 leaves no remainder. An integer is odd when the remainder is non-zero. Both checks take one operation per element.

Canonical test case (from the original FACE Prep problem set):

  • Input: 3 elements, [1, 2, 3]
  • Expected output: Even: 1, Odd: 2

Manual verification:

  • 1 % 2 = 1 — odd
  • 2 % 2 = 0 — even
  • 3 % 2 = 1 — odd
  • Result: 1 even, 2 odd ✓

Three more test cases to run before submitting any implementation:

  • [2, 4, 6, 8] — Expected: Even: 4, Odd: 0
  • [1, 3, 5] — Expected: Even: 0, Odd: 3
  • [] (empty) — Expected: Even: 0, Odd: 0

Confirming by hand takes under a minute and prevents submitting code that passes wrong test cases. Not all legacy problem statements have correct expected outputs; re-derive from first principles rather than trusting the original answer key.

Algorithm: Single Pass with Modulo

The algorithm has five steps:

  1. Read the size n and the n array elements.
  2. Initialize count_even = 0 and count_odd = 0.
  3. Loop from index 0 to n - 1.
  4. For each element: if element % 2 == 0, increment count_even; otherwise increment count_odd.
  5. Print count_even and count_odd.

The C/C++ arithmetic % operator returns the remainder of integer division. For even numbers, the remainder is always 0. For odd numbers, the remainder is 1 (or -1 for negative values in C and Java, which is still non-zero and therefore odd). The condition element % 2 == 0 handles all inputs correctly without any special casing.

There is no sorting step, no auxiliary data structure, and no nested loop. The problem reduces to a linear scan with one binary branch per element.

Code in C, C++, Python, and Java

All four implementations below produce the same output for the canonical input [1, 2, 3].

C

#include <stdio.h>

void countEvenOdd(int arr[], int n) {
    int even = 0, odd = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0)
            even++;
        else
            odd++;
    }
    printf("Even: %d\nOdd: %d\n", even, odd);
}

int main() {
    int arr[] = {1, 2, 3};
    int n = 3;
    countEvenOdd(arr, n);
    return 0;
}

Output:

Even: 1
Odd: 2

C++

#include <iostream>
#include <vector>
using namespace std;

void countEvenOdd(vector<int>& arr) {
    int even = 0, odd = 0;
    for (int x : arr) {
        if (x % 2 == 0) even++;
        else             odd++;
    }
    cout << "Even: " << even << "\nOdd: " << odd << "\n";
}

int main() {
    vector<int> arr = {1, 2, 3};
    countEvenOdd(arr);
    return 0;
}

Output:

Even: 1
Odd: 2

Python

Python’s % operator always returns a non-negative remainder when the divisor is positive, per the Python numeric types documentation. For -3 % 2, Python returns 1, not -1. The odd/even classification is correct in both cases.

def count_even_odd(arr):
    even = sum(1 for x in arr if x % 2 == 0)
    odd  = sum(1 for x in arr if x % 2 != 0)
    print(f"Even: {even}")
    print(f"Odd:  {odd}")

count_even_odd([1, 2, 3])

Output:

Even: 1
Odd:  2

Java

public class EvenOddCount {
    public static void countEvenOdd(int[] arr) {
        int even = 0, odd = 0;
        for (int x : arr) {
            if (x % 2 == 0) even++;
            else             odd++;
        }
        System.out.println("Even: " + even);
        System.out.println("Odd:  " + odd);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        countEvenOdd(arr);
    }
}

Output:

Even: 1
Odd:  2

Verify each implementation against all three test cases from the Problem Statement section before submission.

Time and Space Complexity

MetricValueReason
Time complexityO(n)One left-to-right pass through all n elements
Space complexityO(1)Two integer counters; no auxiliary array or hash map

The algorithm visits each array element exactly once. No element is revisited, sorted, or compared with another. Space stays constant regardless of input size: two counter variables, each holding a single integer.

For a more detailed treatment of space complexity and why constant space matters for constrained environments, see space complexity of algorithms with examples.

The equilibrium index problem applies the same O(n) single-pass pattern with a running prefix sum instead of two counters. It is a natural follow-up: the same time complexity, slightly different bookkeeping per element.

Edge Cases to Verify Before Submission

These four inputs expose the most common defects in placement submissions:

  • Empty array (n = 0): the loop body never executes. Both counters stay at 0. Output: Even: 0, Odd: 0. A standard for (i = 0; i < n; i++) loop handles this automatically; no guard clause is needed.
  • All-even input ([2, 4, 6]): count_odd stays 0. Confirm the output prints Odd: 0, not a blank line or missing field.
  • All-odd input ([1, 3, 5]): count_even stays 0. Same concern.
  • Negative values ([-3, -4]): -4 % 2 == 0 in C, Java, and Python (even); -3 % 2 is -1 in C/Java and 1 in Python (both non-zero, therefore odd). No special handling is needed.

For a related problem that applies a classification rule across array elements (replacing every 0 with 1), see program to replace all 0s with 1. The traversal structure is identical; the classification condition differs.

Placement coding rounds frequently pair even/odd counting with a second array problem. Practising finding all symmetric pairs in an array builds the same loop-and-condition intuition and adds a hash map layer that interviewers often probe for after the first correct answer.

The two-counter pattern here is the simplest classification loop: one pass, one decision per element, two accumulators. Language model output evaluation uses the same structure at a different scale: one pass over responses, one counter per category. TinkerLLM (₹299 entry) runs self-paced modules that connect this kind of array-level thinking to LLM output handling, one project at a time.

Primary sources

Frequently asked questions

What does the modulo operator do with negative inputs?

In C and Java, the sign of the result follows the sign of the dividend: -3 % 2 gives -1, not 1. But -1 is non-zero, so -3 is still classified as odd. Python always returns a non-negative remainder for positive divisors: -3 % 2 gives 1 in Python. Both correctly identify -3 as odd.

What is the time complexity of counting even and odd elements?

O(n), where n is the number of elements. The algorithm makes one left-to-right pass through the array, spending O(1) work per element. No second pass or sorting step is needed.

What happens when the input array is empty?

Both counters start at 0 and stay at 0. The loop body never executes, so the output is Even: 0, Odd: 0. A standard loop using i < n handles this automatically without any guard clause.

Is this problem asked in placement coding rounds?

Yes, typically as a warm-up or first array problem. Placement tests that use AMCAT-based coding screens and many IT service company assessments include a version of even/odd counting to test basic loop, modulo, and counter logic.

Can I use bitwise AND instead of modulo to check odd or even?

Yes. (n & 1) equals 1 when n is odd and 0 when n is even for non-negative integers. For placement compilers, % 2 and & 1 produce equivalent results, but % 2 != 0 is more portable because the bitwise approach is technically undefined for negative values on sign-magnitude representations.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF