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

«
»
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.

  1. /*
  2.  * C++ program to Convert a Decimal Number to Binary 
  3.  * Number using Stacks
  4.  */
  5. #include <iostream>
  6. #include <stdio.h>
  7. #include <conio.h>
  8. using namespace std;
  9. struct node
  10. {
  11.     int data;
  12.     node *next;
  13. }*top = NULL, *p = NULL, *np = NULL;
  14. int x;
  15. void push(int n)
  16. {
  17.     np = new node;
  18.     np->data = n;
  19.     np->next = NULL;
  20.     if (top == NULL)
  21.     {
  22.         top = np;
  23.     }
  24.     else
  25.     {
  26.         np->next = top;
  27.         top = np;
  28.     }
  29. }
  30. int pop()
  31. {
  32.     if (top == NULL)
  33.     {
  34.         cout<<"underflow\n";
  35.     }
  36.     else
  37.     {
  38.         p = top;
  39.         top = top->next;
  40.         x = p->data;
  41.         delete(p);
  42.         return(x);
  43.     }
  44. }
  45. int main()
  46. {
  47.     int n, a;
  48.     cout<<"enter the decimal number\n";
  49.     cin>>n;
  50.     while (n > 0)
  51.     {
  52.         a = n % 2;
  53.         n = n / 2;
  54.         push(a);
  55.     }
  56.     p = top;
  57.     cout<<"resultant binary no:";
  58.     while(true)
  59.     {
  60.         if (top != NULL)
  61. 	    cout<<pop()<<"\t";
  62. 	else
  63. 	    break;
  64.     }
  65.     getch();
  66. }

advertisement
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.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.