Home CPSC 340

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:

DecimalBinary
00
11
210
311
4100
5101
6110
7111
81000
91001
101010
111011
121100
131101
141110
151111
1610000
1710001
1810010
1910011
2010100
2110101
2210110
2310111
2411000
2511001
2611010
2711011
2811100
2911101
3011110
3111111

Details


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.