Decimal to Binary Conversion using Stack

We had discussed here a few applications of stack. And here is another one. Converting positive decimals to binary using a stack. You can use a stack here to reverse the way in which it occurs.

[sourcecode lang=”cpp”]
int num, digit = 0;
cout << "Please enter a decimal: ";
        cin >> num;
        Linked_Stack s;
        while(num > 0)
        {
            digit = num % 2;
            num /= 2;
            s.Push(digit);
        }
     cout<<endl<<"Binary Number: ";
        while(s.Size() > 0)
        {
            cout << s.Pop();
        }

[/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *