C++ Program for Decimal to binary conversion

Program for Decimal to binary conversion

Here, we will discuss decimal to binary conversion in C++.The concept of conversion is very simple.A decimal number can be converted to a binary number by using the repeated division-by-2 method i.e repeatedly divide the decimal number by 2 until no further divisions can be done and the remainder of each division will give us the binary number of the decimal.

Example:9

1) 9/2, Remainder = 1, Quotient = 4, 

2) 4/2, Remainder = 0, Quotient = 2    

3) 2/2, Remainder = 0, Quotient = 1, 

4) 1/2, Remainder = 1, Quotient = 0

        9 in decimal = 1001 in binary

Decimal to binary in C++
Competitive Coding Techniques

Algorithm:-

  1. User gives an input(decimal number).
  2. The input is stored in an int type variable say decimal.
  3. A function convert is called with decimal as a parameter.
    1. A loop is started
      1. The number is divided by 2 and the remainder is stored.

                               rem = n%2;

                           2. The binary number is constructed using the remainder.

                              binary += rem*i;

                  2. The loop will run until the number is not equal to 0.

                     while (n!=0)

     4. The output is printed. 

Decimal to binary conversion in C++

C++ Code:  

//C++ Program
//Decimal to binary conversion

#include <bits/stdc++.h>
using namespace std;

//function to convert decimal to binary
long convert(int n){

long binary = 0;
int i = 1;
//converting decimal to binary
while(n!=0){
int rem = n%2;
n /= 2;
binary += rem*i;
i *= 10;
}
return binary;
}
//main program
int main()
{
int decimal;
long binary;

cout<<"Enter a decimal number: ";
//user input
cin>>decimal;

//calling function
binary = convert(decimal);
cout <<decimal<<" in decimal = "<<binary<<" in binary" <<endl;

return 0;
}
Output

Enter a decimal number: 109

109 in decimal = 1101101 in binary
coding (3)