C++ program to convert decimal to binary

Hello all, today we are going to write a C++ program to convert decimal to binary number, let’s first discuss how we can convert a decimal number to binary number and later we will write the program for the same.

How Program works?

Lets take an example of 11.

Now divide it by 2 and note down the remainder.

  • So.             11 / 2 , Remainder  = 1.
  • Quotient:     5 / 2 , Remainder  = 1.
  • Quotient:     2/2 ,  Remainder  =  0.
  • Quotient:      1/2,  Remainder  =   1.
  • Now Quotient = 0. Stop.

Binary number is the Remainders in reverse order i.e. Binary of 11 = 1011

C++ Program to convert Decimal to Binary:

#include<iostream>
using namespace std;

void binary(int num)
{
    int rem;

    if (num <= 1)
    {
        cout << num;
        return;
    }
    rem = num % 2;
    binary(num / 2);
    cout << rem;
}

int main()
{
    int dec, bin;
    cout << "Enter the number : ";
    cin >> dec;

    if (dec < 0)
        cout << dec << " is not a positive integer." << endl;
    else
    {
        cout << "The binary form of " << dec << " is ";
        binary(dec);
        cout << endl;
    }
    return 0;
}

 

OUTPUT:

C++ program to convert decimal to binary

 

Hope you find it easy, reply in comment if you face any problem in executing the same.

1 thought on “C++ program to convert decimal to binary”

Leave a Comment