Table Of Contents
Previous Section Next Section

Program 55: Sheepish Programming

Farmer Brown, a sheep farmer, had a neighbor who could just look at a flock and tell how many sheep there were at a glance. He wondered how his friend could count so fast, so he asked him.

"Ian, how can you tell how many sheep you have so quickly?"

"Simple," Ian replied. "I just count the legs and divide by 4."

Farmer Brown was so impressed by this that he wrote a short C++ program to verify the Ian sheep-counting algorithm. It wouldn't work for large herds. Why?

  1 /************************************************
  2  * sheep -- Count sheep by counting the         *
  3  *            number of legs and dividing by 4. *
  4  ************************************************/
  5 #include <iostream>
  6
  7 /*
  8  * The number of legs in some different
  9  * size herds.
 10  */
 11 const short int small_herd  =   100;
 12 const short int medium_herd =  1000;
 13 const short int large_herd  = 10000;
 14
 15 /************************************************
 16  * report_sheep -- Given the number of legs,    *
 17  *      tell us how many sheep we have.         *
 18  ************************************************/
 19 static void report_sheep(
 20     const short int legs        // Number of legs
 21 )
 22 {
 23     std::cout <<
 24         "The number of sheep is: " <<
 25                 (legs/4) << std::endl;
 26 }
 27
 28 int main() {
 29     report_sheep(small_herd*4); // Expect 100
 30     report_sheep(medium_herd*4);// Expect 1000
 31     report_sheep(large_herd*4); // Expect 10000
 32     return (0);
 33 }

(Next Hint 165. Answer 1.)

Table Of Contents
Previous Section Next Section