Robson » Little Red Book » Odd or even

Chapter 4 - Question 1

Produce a program that reports whether or not an input integer is odd or even.

Solution 1

<?
   // generate a random number
   $number = mt_rand(1, 100);
   
   // divide the number by two and see if anything is left
   // if so, it must be an odd number, because even numbers can always be divided by two perfectly
   if ($number % 2)
       // show that the number is odd
       echo $number . ' is odd.';
   else
       // show that the number is even
       echo $number . ' is even.';            
?>

Which produces:

32 is even.

Solution 2

Here's a c++ solution:

#include <iostream.h>
int main ()
{
   int i;
   cout << "Type a number or 0 to exit\n>";
   cin >> i;
   if (i%2)
       cout << "That number is odd.\n";
   else
       cout << "That number is even.\n";
   return 0;
}

Log

© 2004-17 robson | cc unless stated