Convert Decimal to Binary in C

Here you will get program to convert decimal to binary in C.

We can convert a decimal number into binary by repeatedly dividing it by 2 and storing the remainder somewhere. Now display the remainders in reverse order.

Also Read: Convert Binary to Decimal in C

Convert Decimal to Binary in C

#include<stdio.h>

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

	return 0;
}

 

Output

Enter a number:10

The binary conversion of 10 is 1010

3 thoughts on “Convert Decimal to Binary in C”

  1. My compiler doesn't like #include or the files in it, but if I take those out it runs. Also the program as is crashes if user inputs 0, and displays a negative sign in front of every 1 if a negative number is input.

    To fix the 0 problem, take out the 1 at the end of 2nd printf("") and make 1st for loop this way: for(i=0;n!=0;i++) and 2nd loop this way: for(j=i-1;j>=0;–j).
    Now it won't crash, but it still won't display a value for 0, to fix this, before 1st for loop use if(n==0) printf("0");
    Now to fix negative value problem: after the (n==0) printf("0"); use else if(n>0) and enclose all that remains (loops, their arguments, printf functions) in curly brackets (also called braces) {}.
    finally, after the positive case is finished, use else
    {
    printf("-");
    ***
    }
    where *** represents all the stuff in positive case, except that in 1st for loop a[i]=d; is replaced with a[i]=-d.
    With these changes made, it should work for any integer positive, negative, or 0 as long as size of integer entered doesn't exceed memory allocated to a variable of type int.

Leave a Comment

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