Sunday, December 27, 2009

Please tell me the coding for this VB.Net program.. (How to check if a number is odd or even?)?

I am making a project just for practice. but I am stuck.. Can anybody tell me the source code for this = Is a number is odd or even?


I am stuck bcuz when i enter 1 it gives even and when i enter 2 it too gives even number :S





My button coding:





dim a as integer


a=textbox1.text


a=textbox1.text/2


if a = 1 then msgbox(';Odd number';)


else


msgbox(';Even Number';)





Help me out please!Please tell me the coding for this VB.Net program.. (How to check if a number is odd or even?)?
Dim a As New Integer


a = TextBox1.Text


If a Mod 2 = 0 Then


MsgBox(';even number';)


Else


MsgBox(';odd Number';)


End IfPlease tell me the coding for this VB.Net program.. (How to check if a number is odd or even?)?
There are functions for trncating roudning etc. But you can just divide by 2 and take the integer of this. And then multiply by 2. If you get the number you started with then the number is even. If you don't then the number is odd.





Example.


1 ... int(1/2) = 0 ... 2*0 = 0 and 0 does not equal 1 so odd


2 ... int(2/2) = 1 ... 2*1 = 2 and 2 equals 2 so even





This will work with any number (up to the limit for integers so you should make your variables Long and use CLng and this will allow a much larger range of numbers).





Dim a As Long


Dim b As Long





a = Text1.Text


b = 2*CLng(Text1.Text / 2)





If a = b Then


MsgBox (';Even number';)


Else


MsgBox (';Odd Number';)


End If

No comments:

Post a Comment