Archive for the ‘Operators’ Category

Determining if a number is odd or even

Thursday, October 18th, 2007

Problem: We wanted to determine if a number is even or odd

Notes: We know that even number end with 0, 2, 4, 6, 8 and odd numbers ends with 1, 3, 5, 7, 9. So how will we know if a number given is an even or odd number in a program..

Solution:

<?
$magic_number = 123568;
if($magic_number % 2 == 0) {
    print "The number is even.";
}  else {
    print "The number is odd.";
}
?>

Explanation: In the program above we use the modulus division. Modulus division unlike the ordinary division (/) returns the remainder instead of the quotient. So we tried modulo dividing the given number by 2 to determine if it is divisible by 2.