basics · beginner · ~15 min

Even or odd

Use the modulo operator + a conditional to classify an integer.

Challenge

Decide whether an integer is even, working correctly for negatives too.

Task

Implement int is_even(int n) that returns 1 when n is even and 0 when n is odd. No main — the grader calls it.

Input

One int argument n, anywhere in the int range (positive, negative, or zero).

Output

1 if n is even, 0 if n is odd.

Example

is_even(4)        ->   1
is_even(-3)       ->   0
is_even(0)        ->   1
is_even(-4)       ->   1

Edge cases

  • Zero is even.
  • Negative even numbers (e.g. -4) return 1; watch out that n % 2 can be -1 for negative odd numbers, so compare to 0, not to 1.

Why this matters

Modulo is one of the most-used operators in real C code. Get comfortable with it now.

Input format

One int argument n.

Output format

1 if n is even, 0 if odd.

Constraints

Negatives must classify correctly: compare n % 2 to 0, not 1.

Starter code

int is_even(int n) {
    /* TODO */
    return 0;
}

Common mistakes

Missing & on scanf. Capitalising Even/Odd. Checking n % 2 == 1 for odd.

Edge cases to handle

Zero is even. Negatives still classify correctly. Non-integer input → exit non-zero.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.