Write a C++ program that changes a decimal number into a binary number. In order
ID: 3679885 • Letter: W
Question
Write a C++ program that changes a decimal number into a binary number. In order to do this, you will write a stack class. The stack class should be implemented using the node class and will used dynamic memory to create nodes – similar to the linked list. The data for the node will be an integer. The stack class should be generic. The code to use the stack and convert the number should be in the main program.
Specific information for class:
Stack class data
* top – points to first Node in list
* count – keeps track of number of Nodes in list Stack class functions
* Any needed constructors * Push – adds a Node to the top of the stack
* Pop –Removes a Node from the top of the stack
* Stack_top – Returns the item at the top of the stack without affecting the stack
* Empty –returns true if stack is empty, false otherwise
Note: Remember that a stack is created in static (automatic memory) and a Node is in dynamic memory.
Requirements for main: In the main program, you will ask the user for a decimal number. You will use the stack program that you wrote to change the decimal number into a binary number and print the result.
Sample: Enter a number: 10 The binary number is : 1010
Explanation / Answer
#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 ";
}
else
{
p = top;
top = top->next;
x = p->data;
delete(p);
return(x);
}
}
int main()
{
int n, a;
cout<<"enter the decimal number ";
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()<<" ";
else
break;
}
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.