C++ Program to Convert Decimal Number to Binary Number Using Stacks

Here, I’m going to teach the topic “C++ Program to Convert Decimal Number to Binary Number Using Stacks” to you using this tutorial. Shall we start the tutorial to learn about it? Come on! Let’s go.

Source Code

/*
* C++ program to Convert a Decimal Number to Binary
* Number using Stacks
*/
#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
struct node
{
int data;
node *next;
}*top = NULL, *p = NULL, *np = NULL;
int x;
void push(int n)
{
np = new node;
np->data = n;
np->next = NULL;
if (top == NULL)
{
top = np;
}
else
{
np->next = top;
top = np;
}
}
int pop()
{
if (top == NULL)
{
cout<<"underflown";
}
else
{
p = top;
top = top->next;
x = p->data;
delete(p);
return(x);
}
}
int main()
{
int n, a;
cout<<"enter the decimal numbern";
cin>>n;
while (n > 0)
{
a = n % 2;
n = n / 2;
push(a);
}
p = top;
cout<<"resultant binary no:";
while(true)
{
if (top != NULL)
cout<<pop()<<"t";
else
break;
}
getch();
}

Final Thoughts 