Program to convert decimal to binary in C++

Written by

Garvit Gulati

Given a decimal number, we have to write a program to calculate its binary equivalent.

# Approaching the problem

To calculate binary equivalent of any decimal number, we divide it by 2 and store the remainder till the number becomes either 1 or 0 and then we write all the remainder in the opposite order of how they were obtained.

2 13 1
2 6 0
2 3 1
1

1310=11012

To implement this, we will initialize an array to store the remainder and keep dividing the number by 2, Then we will print the array in the reverse order.

# Algorithm

  1. Input the decimal number and store it in dec.
  2. Initialize an array bin of size 16 (binary equivalent of -32768 has 16 digits which is the max limit of int).
  3. Divide dec by 2 and store the remainder in the array.
  4. Set dec to the quotient.
  5. Repeat the above two steps till the number is greater than zero.
  6. Print the array in the reverse order and that is the binary equivalent.

Code

#include <iostream>
using namespace std;

int main()
{
    int dec, bin[16], i = 0, j = 0; //dec and bin to store number and ints binary equivalent and i&j are for index maintaining

    cout << "Enter a decimal number\n";
    cin >> dec;

    while (dec > 0) //calculating the binary equivalent and storing it in the array
    {
        bin[i] = dec % 2;
        dec = dec / 2;
        ++i;
    }

    cout << "Binary Equivalent:"; //printing the array in reverse order
    for (j = i - 1; j >= 0; --j)
        cout << bin[j];

    return 0;
}

Output

Enter a decimal number
5
Binary Equivalent:101

Program to convert decimal to binary in C++