Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i tried to use for and approach using loops.

What I have tried:

C++
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
	int a,b,c,d,i;
	b=0;
	c=0;
	scanf("%d",&a);
	printf("%d\n",a);
	
	i=a;
	while(i>=1){
		b=b*10;
		b=b+i%2;
	    i=i/2;
    }
    printf("%d",b);
    return 0;
}
Posted
Updated 23-Aug-19 22:13pm
v4
Comments
Patrice T 23-Aug-19 10:16am    
And you have a question or a problem ?

There are a lot of problems here...
while(i<0){
So it will only enter the loop if the user enters a negative number...
Fix that, and it'll never end:
while(i>0){
i=a;
Because you reset the loop variable each time round the loop...
Fix that, and the bit at the bottom gets you:
c=i%2;


switch(c){

    case '0':
        i=i/2;
    case '1':
        i=(i-1)/2;
}
For two reasons:
1) c will never be equal to a character '0' or '1' - because it's a remainder when divided by 2, so it's a number 0 or 1 and they are different.
Fix that:
c=i%2;
switch(c){
    case 0:
        i=i/2;
    case 1:
        i=(i-1)/2;
}
And it still doesn't work right - though it's a bit better - because it drops through from case 0 to case 1.
Fix that:
c=i%2;
switch(c){
    case 0:
        i=i/2;
        break;
    case 1:
        i=(i-1)/2;
}
And it's almost there - not quite, but getting there - close enough that you should be able to fix the remaining problems.

You could have worked all this out for yourself, just by following exactly what the code was doing - and you will probably need to do that to fix the last problem.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!

Quote:
I tried this but i want to reverse the number and also numbers divisible by 2 are giving a problem.


Yes they will - because you don't know how to "end things"

And reversing the number is exactly what you want to do. That means finding the most significant binary digit and printing from there, or alway printing the same number of binary bits.

I don't know what system you are working on, so I don't know how "big" an integer is: it could be 16 bits:
−32,768 through 32,767
Or 32 bits:
−2,147,483,648 through 2,147,483,647

But if we assume the lower range and ignore negatives then it's pretty simple.

What you need is a shifting mask: first it isolates one bit in the highest position, then you shift it right so next time it looks one bit lower.

So, try this:
cpp"
int x = 32766;
int mask = 0x4000;
int print = 0;
while (mask != 0)
    {
    if (print || (x & mask))
        {
        printf("%d", (x & mask) ? 1 : 0);
        print = 1;
        }
    mask >>= 1;
    }
printf("\n");
Change the initial setting of print and it will "fix" the number of bits to "all 15".
How does it work?
Well ... the initial value of mask is a single bit: bit14 (numbering starts at 0 for the least significant here): in binary that is:
100000000000000
A one followed by fourteen zeros.
Setting print to 0 makes it "false" as far as C is concerned - it has no inbuilt idea of "true" or "false" so any non-zero value is true, zero is false.
We loop while the mask still has bits to check.
Inside the loop we check: if print is non-zero we always print the digit, otherwise we check x with the mask. The & operator in C does a BINARY AND: it returns a value where only those bits that are 1 in both operands, all others are zero. Since mask only contains a single one bit, it isolates the value of that bit in x. (If you don't understand, Wikipedia can help you with pictures)
If we get a "go" from either, we print the binary digit and always set print to non-zero to ensure all subsequent digits are printed regardless of being zero or one.
Then we shift the mask one place right: 0x4000 becomes 0x2000, 0x1000, 0x0800, ... ready for the next digit.
When we have printed bit 0, mask will be one, so the shift will make it zero, and that will stop the loop.

Make sense?
 
Share this answer
 
v2
Comments
Devansh Chowdhury 23-Aug-19 11:33am    
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
int a,b,c,d,i;
b=0;
c=0;
scanf("%d",&a);
printf("%d\n",a);

i=a;
while(i>=1){
b=b*10;
b=b+i%2;
i=i/2;

}
printf("%d",b);



return 0;
}
OriginalGriff 23-Aug-19 11:42am    
You might want to print something inside the loop?
Patrice T 23-Aug-19 12:59pm    
Use Improve question to update your question.
So that everyone can pay attention to this information.
Devansh Chowdhury 23-Aug-19 11:33am    
i tried this but i want to reverse the number and also numbers divisible by 2 are giving a problem.
OriginalGriff 23-Aug-19 12:16pm    
Answer updated.
Quote:
i tried this but i want to reverse the number and also numbers divisible by 2 are giving a problem.

Indeed, your code is reversing the result you want, you need to use another technique.
i%2 extract the 'bit' unit of the number, so you need to include it at the end after all other bits, a little recursive function can do the trick:
C++
int tobin(int v){
    if ( v == 0 )
        return 0;
    int i = v % 2;
    return (tobin(v/2)*10+i);
}

other techniques are possible.
Note that doing the conversion to an integer is limiting the possibles values because you need 10 bits to encode 3 binary bits, so mostly no value beyond 2045 can be encoded this way.
-----
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900