84 720
Assignments Done
99,1%
Successfully Done
In March 2020

# Answer to Question #26587 in C++ for deepak jha

Question #26587
write a c++ program to convert decimal to binary
1
2013-03-19T09:19:52-0400
/* write a c++ program to convert decimal to binary */

#include <iostream>
using namespace std;

// converts integer n to the binary
// and saves binary string to the variable b voiddec2bin(unsigned int n, char * b) {
int i,j,a;
char x;
a=n;
i=0;
do
{
b[i++]='0'+ (a%2); // compute the remainder of division of a by 2
a/=2; // divide a by 2 (integer division)
}
while(a>0);
// now bcontains binary digits of n but in reversed form,
// forinstance: if n=10, then b="0101", so we should reverse b
i--;
// reverse thearray b
// if thelenght of b is 7, then we exchange
// b[0] <=> b[6],
// b[1] <=> b[5],
// b[2] <=> b[4]
for(j=0;j<=i/2; j++)
{
x = b[j];
b[j] =b[i-j];
b[i-j] = x;
}
// set lastbyte in b to zero, so b is a C-string
b[++i]=0;
}

int main()
{
unsigned int n;
char b[200];
// ask to enternumber till the user enter 99999
do
{
cout<< "n = ";
cin>> n;
dec2bin(n,b);
cout<< n << " => " << b << endl;
}
while(n!=99999);
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!