I am trying to learn how to convert ints into binary. it runs but this is the output: Enter a number: 33
New value: 16
Remainder: 1
Current VAlue: -17
Counter: 1
I appreciate any help. Thank you. Ok I am sorry my bad. The output should be: 00100001
#include <stdio.h>
int main()
{
int nv, r, num;
printf("Enter a number: ");
scanf("%d",&num);
int counter=0;
while(num>=0)
{
nv=num/2;
r=num%2;
num=-(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d",num);
}
printf("Counter: %d\n",counter);
}
Is obviously negative, since both
nvandrare positives.I suspect you actually wanted
or:
Also note that your stop condition is
num >= 0– if you do the first change, you will get an infinite loop, since when you reachnum ==0, you will divide by 2, and getnv == num /2 == 0 / 2 == 0and assignnvback tonum(*)Note that also the second change will proide infinite loop:
0 % 2 == 0and0 / 2 == 0, sonum -= (nv + r) == 0 - (0 + 0) == 0