#include<stdio.h>
#include<conio.h>

int main()
{
    int dec,rem,ans=0;
    printf("Enter the Decimal number\n");
    scanf("%d",&dec);
    while(dec>=2)
    {
        rem=dec%2;
        dec=dec/2;
        if(rem==0)
            ans=ans*10;
        else
        ans=(ans*10)+1;
    }
    printf(" binary number is");
    while(ans>0)
    {
        rem=ans%10;
        ans=ans/10;
        printf("%d",rem);
    } 
    getch();
    return 0;
}

this code is not working properly for example for 10 it gives 01, should be 1010

I dont think you code is logically correct. If I give the input as 4, the successive values of rem will be 0,0,1. But the final value in ans will just 1. So in the 2 while loop you will just get 1 as the answer.

The usual method used to convert a decimal to binary number is to store the successive numbers in a stack and then pop the stack. You can avoid the stack if you can think up of bit wise operations to store and retrieve the remainders in a 4 byte integer

>The usual method used to convert a decimal to binary number is to store the successive numbers in a stack...
Or in an array representing each bit.

simply use the format change function in the printf like so, and you will print your numbers as binary

printf("%b", &dec)

This is wrong.

int main()
{   
    int num= 10;
    printf("%d %b %b\n",num,&num,num);   // Wrong
                  
    return 0;
}

The output for this is 10 b b
You can print a number is hexadecimal or octal by using %x and %o respectively but this logic cannot be extended for printing in binary format. In fact I do not believe %b is a legal format specifier for printf

commented: "anonymous" is just some stupid stupid stupid spammer anyway +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.