Thread: stacks and recursion

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    27

    stacks and recursion

    Im confused. I need to write a program that takes a user input number and converts it into binary, octal, and hexidecimal.
    The stack is to be set up as a class.

    6/2 = 3 remainder = 0
    3/2 = 1 remainder = 1
    1/2 = 0 remainder = 1
    110 is the binary equivalent of decimal 6

    Any help to get started would be appreciated....thanks in advance

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    For 6 the process would be like this: (using 4 places)
    Starting from the most significate place
    2^3 = 8. 6>= 8? No. 0.
    2^2 = 4. 6>= 8? Yes 1. 6-4 = 2;
    2^1 = 2. 2>= 2? Yes 1. 2-2 = 0;
    2^0 = 1. 0>= 1? No. 0

    Answer: 0110

    Lets try the number 9
    2^3 = 8. 9>=8? Yes. 1. 9-8 = 1;
    2^2 = 4. 1 >=4? No. 0.
    2^1 = 2. 1>=2? No. 0.
    2^0 = 1. 1>=1? Yes 1. 1-1 = 0;

    Answer: 1001

    For hex its often simpiler to just convert to binary and then convert to hex.

    Bin to Hex:
    0000 - 0x0
    0001 - 0x1
    0010 - 0x2
    0011 - 0x3
    0100 - 0x4
    0101 - 0x5
    0110 - 0x6
    0111 - 0x7
    1000 - 0x8
    1001 - 0x9
    1010 - 0xA
    1011 - 0xB
    1100 - 0xC
    1101 - 0xD
    1110 - 0xE
    1111 - 0xF

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Your first task is apparently to write a stack class, since you're probably not allowed to use the standard one.
    I recommend you use an array
    int _data[32];
    and wrap it with a class which tracks the current top of the stack and provides methods to push and pop values.
    This stack can hold at most 32 values, but that's ok, because an int has only 32 bits, which means that unless your program is supposed to work with numbers > 2^32 you're ok.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    First push all the remainders on the stack:
    Code:
       do {
          Stack.push(num%2);
          num /= 2;
       } while (num > 0);
    Then make another loop to pop each item from the stack and print until the stack is empty.

Popular pages Recent additions subscribe to a feed