How to check if a number is ODD or Even ? [PHP function]

Hey guys!

Long time no seen! Today I had a pleasure of going over myprogrammingblog emails, where many users have asked me to show solutions to different problems. Sorry for not being able to respond earlier, as I had whole bunch of things going on.

From now on, at least for a month, I will be regularly (read as 1 time in 1-2 days) posting some code examples for the problems you have asked me to take a look at. By the way, if you have any interesting problems, which you would like to share with me, please email me at: myprogrammingblog@gmail.com .

Quick Update:

I have opened myprogrammingblog Git repo, where I will be posting code examples discussed in this blog.

Repo URL is :

https://github.com/myprogrammingblog/myprogrammingblog.com/

Now, back to business.

One of the readers ( I am not posting names/nicknames since some people don’t like to be addressed publicly) asked me:

How to check if a number is ODD or Even ?

To solve this problem I will use nice operator, available in most popular programming languages (e.g C/C++/Python/Java/PHP/JavaScript…you name it…) called modulo (%) .

Modulo – finds the remainder of the division.  That’s exactly what we need!

We know that EVEN numbers are those that can be equally (read without a remainder) divided into two groups. By using modulo we can check if the number divided by two does not have a remainder, than it is an EVEN number, otherwise it is ODD.

Bored already ? Here is the code (since no specific language was required, I have used PHP):

In case you need Unit Tests for this function, they are available in the repo.

Thank you for sending me your questions!

Regards,

Anatoly

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. c programming

    Hello,
    Nice article. Thank you for sharing. I also shared a similar article on c programming. I posted a article to check whether a given number is odd or even using c program.

    1. Srinath reddy

      Here is the link for the article of c program to check given number even or odd.

  2. […] Base from: My Programming Blog […]

arrow