Odd+vs+Even+with+MOD

Often, you may need to differentiate between odd numbers and even numbers in Visual Basic. For instance, suppose you have a form that accepts user input. If the number input is odd, you want the program to take specific action. If the number input is even, then you want the program to do something else.

Visual Basic's Mod operator provides the best way to differentiate between odd and even numbers via code. This useful operator returns the remainder of a division. It uses the following structure:

Numerator Mod Devisor

As you can imagine, Visual Basic divides the numerator by the devisor, and returns the remainder. So, the statement

5 Mod 2

divides 5 by 2 and then returns a 1 as the result.

Given that all odd numbers return a 1 when divided by 2, you can simply test for this result. For instance, you might use an If...Then condition, like this:

Dim myNum as Long myNum = Val(Text1)

If myNum Mod 2 Then MsgBox "You've entered an odd number." Else MsgBox "You've entered an even number." End If

Of course, depending on how you prefer to code, you may wish to test for even numbers first in the conditional, in which case you could use the following:

If myNum Mod 2 = 0 Then MsgBox "You've entered an even number." Else MsgBox "You've entered an odd number." End If