Easy–medium · arrays

Even and Odd Count

Read N numbers and report how many are even, how many odd. Two counters marching through one loop — plus a negative-number subtlety the judge will happily test.

At a glanceCount evens and odds with two counters and print "even: E" then "odd: O"; n % 2 is −1 for negative odd numbers, so test against 0 rather than against 1.

Problem

Input: first line has N (1 ≤ N ≤ 1000); second line has N integers (can be negative or zero).

Output: two lines: even: E then odd: O.

Sample:

Input:            Output:
5                 even: 2
1 2 3 4 5         odd: 3

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — parallel counters

Start both at 0, and inside the loop: if (a % 2 == 0) even++; else odd++;. No array needed — like Maximum in an Array, you can process values as they arrive.

Hint 2 — is −3 odd? is 0 even?

-3 % 2 is -1 (the remainder keeps the dividend's sign — see integer division), so test == 0, never == 1: -3 % 2 == 1 is false and would misclassify negatives. And 0 is even — 0 % 2 == 0 is true.

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int even = 0, odd = 0;
    for (int i = 0; i < n; i++) {
        int a;
        cin >> a;
        if (a % 2 == 0) even++;
        else odd++;
    }
    cout << "even: " << even << endl;
    cout << "odd: " << odd << endl;
    return 0;
}

The counters-in-a-loop pattern generalizes to every classification problem: count positives, count grades above 80, count words by length. A good stretch: report the counts of the last digits 0–9 (ten counters — or an array of ten counters, which is the door to bigger ideas).

Deep dive

Why this works

Two independent counters in one pass show that 'several statistics, one traversal' is normal. You rarely need a second loop over the same data.

The cost

O(n) time, O(1) space — one pass fills both counters.

Where it goes wrong

  • n % 2 == 1 is false for negative odd numbers: -3 % 2 is -1. Test n % 2 != 0 instead.
  • Resetting a counter inside the loop throws away everything before the last iteration.

Next step

Buckets instead of two counters: Digit Frequency.

Two things to remember

  • -3 % 2 == -1 in C++: test != 0, not == 1.
  • One pass can fill many counters.
🐞 This version fails — open it and try

n % 2 == 1 is false for negative odd numbers

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int even = 0, odd = 0;
    for (int i = 0; i < n; i++) {
        int v;
        cin >> v;
        if (v % 2 == 0) even++;
        else if (v % 2 == 1) odd++;
    }
    cout << "even: " << even << endl;
    cout << "odd: " << odd << endl;
    return 0;
}