Convert Decimal to Binary in C++

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Basic C++ Program, we will have a look at how to write a c++ program to convert a decimal number to binary. We can convert any decimal number (base-10 (0 to 9)) into a binary number (base-2 (0 or 1)) in the C ++ program.

Decimal Number

Decimal, also called Hindu-Arabic, or Arabic, number system, in mathematics, positional numeral system employing 10 as the base and requiring 10different numerals, the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. It also requires a dot (decimal point) to represent decimal fractions.

Binary Number

In mathematics and digital electronics, a binary number is a number expressed in a base-2 numbering system or a binary number system that uses only two symbols: usually “0” (zero) and “1” (one). The base-2 numbering system is a positional notation with a base 2. Each digit is called a bit.

Decimal to Binary Conversion 

Decimal Binary
1 0
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

How to Convert from Decimal to Binary

  1. In order to convert a number from Decimal Number To Binary Number, you need to Divide the number by 2 and save the remainder(Modulo) in an array. 
  2. After that, Divide the number by 2 through / (division operator)
  3. You need to keep dividing the number until the number is the equivalent of less than zero.

Convert Decimal to Binary In C++

#include <iostream>  

using namespace std;  

int main()  

{  

int a[10], n, i;    

cout<<"Enter the number to convert: ";    

cin>>n;    

for(i=0; n>0; i++)    

{    

a[i]=n%2;    

n= n/2;  

}    

cout<<"Binary equivalent= ";    

for(i=i-1 ;i>=0 ;i--)    

{    

cout<<a[i];    

}    

}  

Output:

Enter the number to convert: 5

Binary equivalent= 101

Leave a Comment

Your email address will not be published. Required fields are marked *