This C++ program, using a stack, displays the bits of a binary number when the corresponding decimal number is entered as input.
Here is the source code of the C++ program to display a linked list in reverse. The C program is successfully compiled and run on DevCpp, a C++ compiler. The program output is also shown below.
/*
* 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<<"underflow\n";
}
else
{
p = top;
top = top->next;
x = p->data;
delete(p);
return(x);
}
}
int main()
{
int n, a;
cout<<"enter the decimal number\n";
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();
}
Output enter the decimal number 1388 resultant binary no:1 0 1 0 1 1 0 1 1 0 0
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Computer Science Internship
- Apply for Data Structure Internship
- Apply for Information Technology Internship
- Practice Design & Analysis of Algorithms MCQ
- Buy Programming Books