Wednesday 28 March 2012

ASP: calculate if a number is odd or even

   


In this short post I will explain something that I see asked often on forums and ASP help site.
How can we calculate if a number is even or odd?

The question is quite easy and the answer is hidden in the MOD function. I've talked about that function in a past article (ASP: resulting recordset in two columns), where we used the MOD function in order to create a two columns table and display data using the same table.

As a reminder, "the MOD function provides the remainder value in a division. The remainder is what's left over after you do a division."
Apart from the fact that I'm starting to quote myself - and I probably should talk to my wife who is a psychotherapist, it is quite easy, even if you are not a math expert, to understand how we can benefit from the MOD function to determine if a number is odd or even.

Basically if the number devided by two has no remainder, the number is even, otherwise is odd. We can then build a short snippet to get a result:
<%
if number MOD 2 = 0 then
  response.write ("The number " & number & " is even")
else
  response.write ("The number " & number & " is odd")
end if
%>
We might need to determine if a number is odd. In this case we will use:
<%
if number MOD 2 then
  response.write ("The number " & number & " is odd")
end if
%>
And that is all for today.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.