# Stack Exercise

### Objective

To be able to utilize stacks in a C++ program.

### Task

For this lab exercise, you will write a program that converts a decimal number into binary. Your program will read in a decimal number from the user, and print it back out in binary representation.

For the Big Int project, you had to break a decimal number up into digits using a loop something like this:


while(number != 0) {
int digit = number % 10;
number = number / 10;
}


Breaking a number into bits will work the same way except that instead of using 10 for the division and modulus, we will use 2 instead.

If we use this technique to print out the bits, we will get them in the reverse order of what they should be. This is because, in the loop, we start with the least significant bits and move onto the most significant.

In order to avoid this, we will push each bit onto a stack. Then at the end of the program, we will pop them all off to get them in the correct order.

So that you can test your program, here are the first 32 numbers in decimal an binary:

 Decimal Binary 0 0 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 9 1001 10 1010 11 1011 12 1100 13 1101 14 1110 15 1111 16 10000 17 10001 18 10010 19 10011 20 10100 21 10101 22 10110 23 10111 24 11000 25 11001 26 11010 27 11011 28 11100 29 11101 30 11110 31 11111

### Details

• Your program should start by inputting an integer with cin >>.
• Next you should write a loop that pushes the bits of the number onto a stack one at a time.
• You can use either the ArrayStack or ListStack from class as your stack - just copy and paste the code into your file.
• Lastly, you should write another loop that pops everything off of the stack and prints the bits out.

### Submitting

When your program works, email the code to ifinlay@umw.edu.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.