Sample Program Using a Stack


//  this program will read numbers in base 10 and output them in base 2
//
//  the number is converted by dividing by 2 repeatedly and saving the 
//  remainders. The base 2 number is formed by taking the remainders in the 
//  opposite order to that in which they were generated. a stack is used to 
//  reverse the order of the remainders.

#include <iostream.h>
#include "Stackarr.h"

int main()
{
   int num;
   int remainder;
   char response;
   int ok;
   Stack remStack;

   do
   {

// repeatedly convert numbers until the user is done
      cout << "Enter a positive integer in decimal: ";
      cin >> num;
      ok = 1;

// divide by 2 and push remainder until number is reduced to 0
      while (num != 0 && ok)
      {
         remainder = num % 2;
         ok = remStack.push(remainder);
         num = num / 2;
      }

// if the stack didn't overflow, pop the remainders and print them
      if (ok)
      {
         cout << "Binary representation: ";
         while (!remStack.isEmpty())
         {
            ok = remStack.pop(remainder);
            cout << remainder;
         }
         cout << endl;
      }
      else

// print error message if stack overflowed
         cout << "Error in conversion: stack not large enough\n";

// see if user wants to convert again
      cout << endl << endl;
      cout << "Convert another number (Y or N)? ";
      cin >> response;
   }
   while(response == 'Y' || response == 'y');
}

Output


Enter a positive integer in decimal: 13
Binary representation: 1101


Convert another number (Y or N)? y
Enter a positive integer in decimal: 125
Binary representation: 1111101


Convert another number (Y or N)? y
Enter a positive integer in decimal: 2001
Binary representation: 11111010001


Convert another number (Y or N)? n


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page