# Decimal to Binary equivalent using Stack ADT.

decimal number to its binary equivalent, Stack ADT,
Write C++ code to convert a decimal number to its binary equivalent using Stack ADT.

As stack is a LIFO data structure, we can retrieve the content of stack in the reverse order of storing. This property of stack is used in this application. To convert a decimal number to its binary equivalent, we repeatedly divide the decimal number by 2 and the remainder of division (either 0 or 1) is pushed in to the stack, until the number becomes zero. When the division is completed, pop out all the elements from the stack, which will give the binary equivalent.
Algorithm:
/ * This algorithm outputs the binary equivalent of a decimal number, num. */

void convert(integer num)
{
stack<integer> stack1;
int rem,n,y,n=num;
while(n>0)
{
//push remainders to stack.
rem = n%2;
stack1.push(rem);
n=n/2;
}
while(!stack1.isEmpty)
{
//pop all remainders from stack
y=stack1.pop();

cout<<y;
}
}

Thanks
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..