EN
C# / .NET - check if number is odd
7 points
In this short article, we would like to show how check if number is odd using C# / .NET.
Quick solution:
xxxxxxxxxx
1
int number = 5;
2
3
if (number % 2 != 0)
4
{
5
// ...
6
}
Odd numbers:
xxxxxxxxxx
1
... -7 -5 -3 -1 1 3 5 7 ...
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(String[] args)
6
{
7
Console.WriteLine( NumberUtils.IsOdd(0) ); // false
8
Console.WriteLine( NumberUtils.IsOdd(1) ); // true // odd
9
Console.WriteLine( NumberUtils.IsOdd(2) ); // false
10
Console.WriteLine( NumberUtils.IsOdd(3) ); // true // odd
11
Console.WriteLine( NumberUtils.IsOdd(4) ); // false
12
Console.WriteLine( NumberUtils.IsOdd(5) ); // true // odd
13
14
Console.WriteLine( NumberUtils.IsOdd(-1) ); // true // odd
15
Console.WriteLine( NumberUtils.IsOdd(-2) ); // false
16
Console.WriteLine( NumberUtils.IsOdd(-3) ); // true // odd
17
Console.WriteLine( NumberUtils.IsOdd(-4) ); // false
18
Console.WriteLine( NumberUtils.IsOdd(-5) ); // true // odd
19
}
20
}
21
22
public class NumberUtils
23
{
24
public static bool IsOdd(int number)
25
{
26
return number % 2 != 0;
27
}
28
}
In this section, you can find solution that uses bitwise operator.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main(String[] args)
6
{
7
Console.WriteLine( NumberUtils.IsOdd(0) ); // false
8
Console.WriteLine( NumberUtils.IsOdd(1) ); // true // odd
9
Console.WriteLine( NumberUtils.IsOdd(2) ); // false
10
Console.WriteLine( NumberUtils.IsOdd(3) ); // true // odd
11
Console.WriteLine( NumberUtils.IsOdd(4) ); // false
12
Console.WriteLine( NumberUtils.IsOdd(5) ); // true // odd
13
14
Console.WriteLine( NumberUtils.IsOdd(-1) ); // true // odd
15
Console.WriteLine( NumberUtils.IsOdd(-2) ); // false
16
Console.WriteLine( NumberUtils.IsOdd(-3) ); // true // odd
17
Console.WriteLine( NumberUtils.IsOdd(-4) ); // false
18
Console.WriteLine( NumberUtils.IsOdd(-5) ); // true // odd
19
}
20
}
21
22
public class NumberUtils
23
{
24
public static bool IsOdd(int number)
25
{
26
return (number & 1) != 0;
27
}
28
}