please check

R

raghu

//program to print binary of an integer

#include<stdio.h>
int main(void)
{
int i=3,j;
for(j=2;j>=0;j--)
{
i=i%2;
printf("%d",i)
}
}

On turbo C compiler I'm getting output as 111 as opposed to 011
if i=2 & 4 output is 000.

Please correct me if I'm wrong in writing the program

Thanks in advance
 
M

mark_bluemel

raghu said:
//program to print binary of an integer

#include<stdio.h>
int main(void)
{
int i=3,j;
for(j=2;j>=0;j--)
{
i=i%2;
printf("%d",i)
}
}

On turbo C compiler I'm getting output as 111 as opposed to 011
if i=2 & 4 output is 000.

Please correct me if I'm wrong in writing the program

Here's how I learnt to debug this sort of problem (many many years ago
in COBOL...) :-

Sit down with a piece of paper and a pen, and pretend you're the
computer executing this program. What will the values of the variables
be at each iteration of the loop?
 
A

Andrew Poelstra

//program to print binary of an integer

#include<stdio.h>
int main(void)
{
int i=3,j;
for(j=2;j>=0;j--)
{
i=i%2;
printf("%d",i)
}
}

On turbo C compiler I'm getting output as 111 as opposed to 011
if i=2 & 4 output is 000.

Please correct me if I'm wrong in writing the program

Well, I'll fix your formatting and your spurious use of '//' comments
(They restrict portability and benefit nothing. If you needed some real
features of C99, which is the latest but not well-supported standard, it
would be a different story. But I'm not starting that debate again...)

/* program to print binary of an integer */
#include <stdio.h>

int main(void)
{
int i = 3, j;
for(j = 2; j >= 0; j--)
{
i %= 2;
printf("%d",i)
}
}
/* End */

i will always be 1. Taking it modulo 2 several more times won't change
that fact. However, the missing semicolon at the end of your printf()
suggests to me that you didn't copy-and-paste your code, but instead
tried to type it out as best you could.

Post your real code and we'll help you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,161
Latest member
GertrudeMa
Top