Select Page

In C#, an integer is even when number % 2 == 0. Otherwise, it is odd. This test works for positive integers, negative integers, and zero.

Check even or odd with the remainder operator

The % operator returns the remainder after division. For example, 5 % 2 is 1, 6 % 3 is 0, and 10 % 4 is 2.

Run this complete console example:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 5, 6, 0, -3, -4 };
        foreach (int number in numbers)
        {
            if (number % 2 == 0)
            {
                Console.WriteLine($"{number} is even");
            }
            else
            {
                Console.WriteLine($"{number} is odd");
            }
        }
    }
}
5 is odd
6 is even
0 is even
-3 is odd
-4 is even

Why compare the remainder with zero?

Even integers divide by two with no remainder. Zero is even because 0 % 2 is zero.

For integer operands in C#, a nonzero remainder has the same sign as the left operand. That means -3 % 2 is -1. To test for odd numbers directly, use number % 2 != 0. Comparing with 1 would miss negative odd numbers.

Read a number from text

If your number comes from a text box or console input, convert the string with int.TryParse before testing it. The example above uses int; parity is a property of integers, so establish how to handle fractional input before applying this test.

Learn how the quotient differs from the remainder in multiplication and division in C#.

Reference

See Microsoft’s remainder operator reference for the rules for integer and floating-point operands.

Share This