Justin Farr - 1 year ago 73

C++ Question

I was tasked with writing some code that will take a user input and convert the number to its binary number. I have written some code so far, but am having one issue. I have to use a for loop and the quotient-remainder method. When I output the remainder(binary), it is not printing the last digit.

The question I'm asking is: What would I have to change in my for loop to make it print out the last digit of the binary number?

`int main()`

{

int num;

int rem;

cout << "Please enter a number: ";

cin >> num;

for (int i = 0; i <= (num + 1); i++)

{

num /= 2;

rem = num % 2;

cout << rem;

}

_getch();

return 0;

}

Any help is appreciated, Thank you!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You lose the last binary number when you start your algorithm by dividing `num`

by 2. To avoid this issue, you should exchange both instructions `num /= 2;`

and `rem = num % 2;`

Your loop also iterates too many times: in fact you can stop when `num == 0`

. The following code is not valid for inputs that are <= 0.

```
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
while (num != 0)
{
rem = num % 2;
num /= 2;
cout << rem;
}
cout << std::endl;
return 0;
}
```

If you want to write it in the right order, you should first compute the log of your number in base 2. The following solution uses a number `index`

that starts with '1' and that has '0' after:

```
int main()
{
int num;
int rem;
cout << "Please enter a number: ";
cin >> num;
if (num > 0) {
int index = 1;
while (index <= num)
index *= 2;
index /= 2;
do {
if (num >= index) {
cout << '1';
num -= index;
}
else
cout << '0';
index /= 2;
} while (index > 0);
cout << std::endl;
}
else
cout << '0';
cout << endl;
return 0;
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**