SOURCE FILE: 6.07Hailstone.cpp


//    
// Example 6.7. Hailstones problem:  For positive input     
// integer n, do the following until n is 1:  If n is even,    
// change n to n/2, else change n to 3 * n + 1   
//    
   
#include <iostream.h>
#include <iomanip.h>
  
int main(void)   
{   
   int readn(void);   
   void hailstones(int);   
   
   int n;   
   
   n = readn();   
   if (n <= 0)   
      cout << n << " is not positive.  Please run again.\n";
   else   
      hailstones(n);
   
   return 0;   
}   
   
//   
// Function to print directions and read a value for n   
// Pre:  none   
// Post: Directions have been displayed, and    
//       the user input has been returned.   
//    
   
int readn(void)   
{   
   int n;   
      
   cout << "This program prints the hailstone sequence.\n";
   cout << "Please enter a positive integer: ";
   cin  >> n;
   
   return n;   
}   
   
//   
// Given a positive integer n, function to print hailstone 
// sequence with step numbers.  When the sequence arrives 
// at 1, it prints the original n and the number of steps. 
// Pre:  n is a positive integer.   
// Post: Hailstone sequence has been displayed.   
//    
   
void hailstones(int n)   
{   
   int nsave,           // original n 
       step = 0;        // step number 
   
   nsave = n;           // save original n 
   
   // Generate hailstone sequence 
   while (n > 1)   
   {   
      if (n % 2 == 0)   // n even 
         n /= 2;   
      else              // n odd 
         n = 3 * n + 1;   
      step++;   
      cout << "Step " << setw(4) << step << ": n = " 
           << setw(5) << n << endl;
   }   
   cout << endl << nsave << " went to 1 in "
        << step << " steps.\n";
}