Check for odd and even numbers
At some point we'll all come across a situation where we need to determine if a number is odd or even. Here's the c# code to do it.
using System;
public static bool IsOdd(int value)
{
return value % 2 != 0;
}
So lets deconstruct how this works.
The % operator is the key. It divides the first operator by the second and returns the difference. So 5 % 2 = 1. Five can be divided by 2 twice, leaving 1 and the remainder.
So applying % 2 to any even number will return 0. Applying % 2 to any odd number will return 1.