Determine whether a number is even or odd
Determine whether an integer is even or odd, including when the value is negative.
Course progress
Problem 11 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
number = -7
Expected output
Odd
What is happening?
Dividing -7 by 2 leaves a non-zero remainder, so the number is odd even though it is negative.
Solution strategy
Build the right mental model
An integer is even when division by 2 leaves a remainder of zero. Every other integer is odd.
Core concepts
modulo · conditions
Complexity
Time O(1), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for even-or-odd
using System;
class Program
{
static string EvenOrOdd(int number)
{
return number % 2 == 0 ? "Even" : "Odd";
}
static void Main()
{
Console.WriteLine(EvenOrOdd(-7));
}
}Knowledge check
Questions students often ask
What is the main idea behind determine whether a number is even or odd?
An integer is even when division by 2 leaves a remainder of zero. Every other integer is odd.
What is the time and space complexity of this solution?
Time O(1), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.