C++ Program for Decimal to binary conversion

Program for Decimal to binary conversion

Here we will discuss how to convert a decimal number into a binary number using C++ Programming language.

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

Step 1: 9/2, Remainder = 1, Quotient = 4

Step 2: 4/2, Remainder = 0, Quotient = 2

Step 3: 2/2, Remainder = 0, Quotient = 1

Step 4: 1/2, Remainder = 1, Quotient = 0

9 in decimal = 1001 in binary

Program to Convert decimal to binary

Working

Let’s see how the code works:

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

        rem = n%2;

      • The binary number is constructed using the remainder.

        binary += rem*i;

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

        while (n!=0)

  • The output is printed. 

C++ Code

//C++ Program
//Decimal to binary conversion
#include <iostream>
#include <math.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

Please Login/Signup to comment