Thursday, 13 December 2012

How to find odd and even numbers in C#

How to find odd and even numbers in C#

 

There are 2 methods find even or odd numbers in C#.

 

  Method 1: Modulus operator %

  Method 2:   BitField Operator &

Method 1:  Modulus Operator %

  Note:Find even or odd with modulus operator,When divided by 2 if remainder of the number is 0, then number is even otherwise odd.
    for  number 3  remainder is 1 so odd  3%2=1
    for number 4 remainder is 0 so even.  4 %2=0

 public bool isEven(int num)
       {
           if (num % 2 == 0) return true;
           else return false;
       }

  Method 2:   BitField Operator &

       public bool isEvenUsingBitFields(Int32 num)
       {
           if ((num & 1) ==0) return true;
           else return false;
       }

 This examples uses bit operator And. If result is 0 then Even number, otherwise Odd Number.