Convert Decimal to Binary in C++

Here you will get the program to convert a number from decimal to binary in C++.

How to convert decimal numbers to binary?

  • Divide the number by 2 and save the remainder somewhere.
  • Divide the quotient by 2 again and save the remainder somewhere.
  • Repeat the process until 1 is left as the quotient.
  • Now write the remainder in reverse order.

This program can only convert nondecimal numbers.

Also Read: Convert Binary to Decimal in C++

C++ Program to Convert Decimal to Binary

#include<iostream>

using namespace std;

int main()
{
	int d,n,i,j,a[50];
	cout<<"Enter a number:";
	cin>>n;
	cout<<"\nThe binary conversion of "<<n<<" is 1";
	
	for(i=1;n!=1;++i)
	{
		d=n%2;
		a[i]=d;
		n=n/2;
	}
	
	for(j=i-1;j>0;--j)
		cout<<a[j];
		
	return 0;
}

Output:

Enter a number:5
The binary conversion of 5 is 101

2 thoughts on “Convert Decimal to Binary in C++”

Leave a Comment

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