[c]Decimal to binary

#include <stdio.h>

int main()
{
    /*
    Find the binary of decimal. Example: if 4.
    Find the remainder of a number divider by 2.
    4%2 = 0 >> 1st index.
    2%2 = 0 >> 2nd index.
    1%2 = 1 >> 3rd index.
    Then reverse the index enumerate the number backwards.
    bin[i--] until looks like this 100.
    */
    int i, bin[10], num, count=0;
    printf("Enter a number");
    scanf("%d",&num);
    while(num!=0)
    {
        bin[count] = num%2;//store the remainder.
        count++;
        num /= 2; 
    }
    for(i=count-1;i>=0;i--)//enumerate backwards
    {
        printf("%d",bin[i]);
        
    }
    
    return 0;
}
Advertisements
This entry was posted in General stuffs. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s