Wednesday, April 14, 2010

C++ exercises: BaseOut


Q: Write a function
   void BaseOut(unsigned int n, int b);
that outputs n in the base b, 2 <= b <= 10. Print each number in the range 2<=n<=50 in base 2, 4, 5, 8 and 9.

#include <iostream>
                                                                                
using std::cout;
using std::endl;
                                                                                
void BaseOut(unsigned int n, int b)
{
   int a[64];  // 64 may not be enough if n is bigger.
                                                                                
   // Check the range of b.
   if (b > 10 || b < 2)
   {
      cout << "Error: base out of range - " << b << endl;
      return;
   }
                                                                                
   cout << n << " in the base " << b << ":";
                                                                                
   // Calculate and store the result in a[].
   size_t i;
   for (i = 0; n > 0; i++)
   {
      if (sizeof(a) <= i)
      {
         cout << "Error: " << n << " is too big" << endl;
         return;
      }

      a[i] = n % b;
      n /= b;
   }
                                                                                
   // Output the result.
   for (size_t j = 1; j <= i; j++)
   {
      cout << a[i-j];
   }

   cout << endl;
}
                                                                                
int main()
{
   for (size_t i = 2; i <=50; i++)
   {
      BaseOut(i, 2);   // i in the base 2
      BaseOut(i, 4);   // i in the base 4
      BaseOut(i, 5);   // i in the base 5
      BaseOut(i, 8);   // i in the base 8
      BaseOut(i, 9);   // i in the base 9

      cout << endl;
   }

   return 0;
}

No comments:

 
Get This <