#include<stdio.h>
<strong>int</strong> main() // main's return type is int
{
/* ... */
b= m%2; // I'm assuming you mean <strong>n%2</strong>
while( b!= 0) // this will check if <strong>n</strong> is even or odd. if it's even, the loop will be skipped. See below.
The loop has to continue until the b==0.
You probably mean until n == 0. b is just the LSB of n, which could become 0 at any point during the operation. Also, if you've already done b = b%2 , doing it repeatedly will never change the value of b.How do I have the b @ every loop recorded for the final output? Or do I have to include this in the loop :
b = b%2 .
You'll probably have this in the loop. See above about using n%2 vs. using b%2 (you'll probably want b = n % 2; ). And think about what you need to do to n as well.But I still can't figure out a way to print all the b's @ every stage of the loop after the loop has ended.
Why not just print them inside the loop?
Infarction
Posting Virtuoso
1,580 posts since May 2006
Reputation Points: 683
Solved Threads: 53
While (b not 0)
{
test odd or even
{
save the result (0 or 1) in an array
}
shift b right 1 bit (or divide by 2)
}
output the array from last value to the first.
If you use the division version,b should be an unsigned value.
Alternate for the loop, if your value is 32 bits, simply use a for loop and you won't have to worry about signed/unsigned and your output would be a full 32 bits.
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
b = decimal;
while ( b != 0 )
{
n = n * 10 + ( b % 2 );
b /= 2;
}
while ( n != 0 )
{
binary = binary * 10 + ( n % 10 );
n /= 10;
}
The above is one of the method where you can change decimal number to binary. It depends on how to apply the logic into a programming language. The first loop above is to convert the decimal number to binary. However, the binary is in a reverse order. Therefore, you will need the second loop to reverse it and get the answer. You can try the mathematical calculation manually so that you can understand it more clearly. Hope it helps you.
rinoa04
Junior Poster in Training
84 posts since Sep 2006
Reputation Points: 52
Solved Threads: 4