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

 

Output

Enter a number:10

The binary conversion of 10 is 1010

3 thoughts on “Convert Decimal to Binary in C

  1. Nightdreamer

    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.

    Reply

Leave a Reply

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