Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,412 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,454 people online right now. Registration is fast and FREE... Join Now!




int to binary

 
Reply to this topicStart new topic

int to binary, garbage output

avinandanaot
15 Oct, 2008 - 06:21 AM
Post #1

New D.I.C Head
*

Joined: 14 Oct, 2008
Posts: 13


My Contributions
#include<stdio.h>
#include<conio.h>
void main()
{
int i,k,x[16];
printf("\n Enter any integer number");
scanf("%d",&k);
for(i=0;i<16;i++)
{
x[15-i]=(k>>i)&1;
for(i=0;i<16;i++)
{
printf("%2d",x[i]);
}
}
}

please help me find out the mistake
User is offlineProfile CardPM
+Quote Post

jderecho
RE: Int To Binary
15 Oct, 2008 - 07:02 AM
Post #2

New D.I.C Head
*

Joined: 23 Jul, 2008
Posts: 22



Thanked: 3 times
My Contributions
You have the general idea, but you were outputting your output array before it was built.

CODE

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

void main()
{
    int i,k,x[16];
    printf("\n Enter any integer number ");
    scanf("%d",&k);

               //  Build output here
    for( i=0;i<16;i++ )
    {
        x[15-i]=(k>>i)&1;  
    }
                // Output result here
    for( i=0;i<16;i++ )
    {
        printf("%2d",x[i]);  
    }
}


Move the output loop outside the build loop, and it does what you wanted. Hope this helps.

Juan
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/2/08 12:26PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month