Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Quick one - how can i tell if an integer is odd or even?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi,
probably a simple one...

if x = odd then..
else if x = even then..

how do i do this..

thanks for your help..
 
Hi Dave

I am a newbie to PHP (total time 1 day) so I will not be able to give you the PHP code, but in Cold Fusion there is a mathematical operator that I think is fairly common to most languages (and I would imagine is available in PHP), namely modulus. Modulus gives you the remainder and works as follows :

11 Modulus 4 = 3 i.e. 4 goes into 11 twice with a remainder 3

Therefore to solve your problem the pseudocode should look something like this:

IF x MOD 2 > 0 (odd)

Then.....

ELSE (even)

So, all you need to do is look up the PHP equivalnt of modulus.

Cheers

Roardood
 
<?php
$i=0;
while ($i < 10)
{
echo &quot;$i&quot;;
if ($i%2) {
echo &quot;Number is Odd<hr>&quot;;
} else {
echo &quot;Number is Even<hr>&quot;;
}
$i++;
}
?> ***************************************
Party on, dudes!
[cannon]
 
Yes, PHP's modulo operator is expressed as &quot;%&quot;, so you could use the following function:

Code:
function is_odd($var)
{
 if($var % 2 > 0){
 // we have a remainder, so value is odd
 return 1;
 }
 else{
 return 0;
 }
}

So, to check if any value is odd, you would just do
Code:
if(is_odd($my_variable))
{
  //do whatever you want with an odd number
}
else{
  //do whatever you want with an even number
}
[code]

I know that it is just as simple to do if($myvar % 2 > 0), but it the is_odd() function might make your code a little more &quot;self_documenting&quot;. -------------------------------------------

&quot;Now, this might cause some discomfort...&quot;
([URL unfurl="true"]http://www.wired.com/news/politics/0,1283,51274,00.html)[/URL]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top