### Decimal To Binary Conversion | Using Stack

To convert decimal number to its equivalent binary number we divide the decimal number with the base of binary number which is 2 and then print the remainder in reverse order.

We use stack to store the remainders and then pop the stack to print the equivalent binary number.

For example:- Decimal Number : 10 Equivalent Binary Number : 1010

**Step 1:**

Divide the decimal number until the quotient becomes 0 and push the remainder into the stack. So, stack store the remainder in the order of LIFO.

According to the above fig. we divide number 10 with divisor 2 and push remainder 0 into the stack. Similarly, we divide quotient 5 with divisor 2 and push remainder 1 into the stack and repeat this procedure until the quotient becomes 0 as shown in above fig.

**Step 2:**

Perform pop () operation until the stack is empty and popped the top element and display it. As a result, the remainder is print in reverse order which is equivalent to its binary number.

According to the above fig. we pop() the top most element (which is the last remainder pushed into the stack) i.e. 1 and print it into the screen. Similarly, again pop() the next top most element which is 0 from the stack and display it into the screen and repeat this procedure until the stack is empty as shown in above fig.

**Code :-**

#include <iostream> using namespace std; #define SIZE 64 //Total bit size is 64 class stack{ private : int item[SIZE]; int top; public : stack(){ top=-1; } bool isEmpty(){ return top==-1; } void push(int value){ item[++top]=value; } int pop(){ return item[top--]; } }; void equivalentBinary(int num){ const int base=2; //Base of binary number is 2 int temp,rem; stack s; temp=num; while(num){ //Push remainder into stack rem=num%base; s.push(rem); num=num/2; } cout<<"Equivalent binary of decimal number "<<temp<<"= "; while(!s.isEmpty()){ //Pop the remainder and print it cout<<s.pop()<<" "; } } int main() { int num; cout<<"Enter a decimal number "; cin>>num; equivalentBinary(num); return 0; }

CommentsNo comment yet.