Decimal to binary conversion C++ program { Method 1 }
For the conversion of decimal to binary, what we do. We divide number by 2 until we get 0 and then write the remainders. see the image.
Here we are doing same. First we divide number by two and store remainders in array. then print array reverse.
For example number is 23 and array is bin[] then
Here we are doing same. First we divide number by two and store remainders in array. then print array reverse.
For example number is 23 and array is bin[] then
23%2 = 1; bin[0] = 1; 23/2 = 11;
11%2 = 1; bin[1] = 1; 11/2 = 5;
5%2 = 1; bin[2] = 1; 5/2 = 2;
2%2 = 0; bin[3] = 0; 2/2 = 1;
1%2 = 1; bin[4] = 1; 1/2 = 0;
11%2 = 1; bin[1] = 1; 11/2 = 5;
5%2 = 1; bin[2] = 1; 5/2 = 2;
2%2 = 0; bin[3] = 0; 2/2 = 1;
1%2 = 1; bin[4] = 1; 1/2 = 0;
/* C++ program for decimal to binary conversion */ #include<iostream> using namespace std; int main() { /* array to store binary number */ int n,i,j,bin[32]; cout<<"Enter a decimal number: "; cin>>n; for(i=0;n!=0;i++) { int rem=n%2; bin[i]=rem; //store binary number in array n=n/2; } cout<<"Binary number is "<<endl; for(j=i-1;j>=0;j--) { cout<<bin[j]; } return 0; }