Base-10 to Base-2 Conversion

I want this Program to convert any base-10 number into binary number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>

using namespace std;

typedef struct Node
{
	int info;
	Node *next;
}* nptr;

nptr top,np;

int main()
{
	top=NULL;
	int a,b;
	cout<<"\nProgram to Convert Decimal Number to Binary Number :";
	cout<<"\n******* ** ******* ******* ****** ** ****** ******";
	cout<<"\n\nEnter A Number : ";
	cin>>a;
	b=a;
	do
	{
		np=new Node;
		np->next=top;
		top=np;
		np->info=(b%2);
		b=((b-(b%2))/2);
		delete np;
	}while (b>=0);
	cout<<"\nThe Binary Equivalent of ("<<a<<") is : ";
	while(top!=NULL)
	{
		cout<<top->info;
		np=top;
		top=top->next;
		delete np;
	}
}


What is the error in the program ?
Last edited on
One error is that in your do-while loop once b gets to zero, it stays at zero: INFINITELY!

So change the do-while to state:

1
2
3

    while b > 0;


Also, take out the delete np on line 29.
Last edited on
A linked list seems like overkill for this problem.
This can be solved simply with a std::string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include <string>
using namespace std;

int main()
{   string  rslt;

	int a,b,c;
	cout<<"\nProgram to Convert Decimal Number to Binary Number :";
	cout<<"\n******* ** ******* ******* ****** ** ****** ******";
	cout<<"\n\nEnter A Number : ";
	cin>>a;
	b = a;
	do
	{   c = b % 2;  //  Get least significant digit
	    rslt.insert (0, 1, c+'0'); // insert ASCII value
		b /= 2;
	} while (b > 0);
	cout<<"\nThe Binary Equivalent of ("<<a<<") is : " << rslt << endl;
    system ("pause");
}


Topic archived. No new replies allowed.