### Decimal to Binary number

Here is a program to convert decimal to binary-

 ``123456789101112131415161718192021222324252627282930313233`` ``````#include using namespace std; void binary(int); int main(void) { int number; cout << "Please enter a positive integer: "; cin >> number; if (number < 0) cout << "That is not a positive integer.\n"; else { cout << number << " converted to binary is: "; binary(number); cout << endl; } } void binary(int number) { int remainder; if(number <= 1) { cout << number; return; } remainder = number%2; binary(number >> 1); cout << remainder; }``````

I'm in a bit difficulty to understand the function binary().

Say, I would like to convert Decimal 11 to binary number. binary(number >> 1) uses bit-wise operation and generates values 5,2 and 1.For the number 11, its goes to the binary ()function recursively with with 5 then, 2 and 1. My question is then it should print the binary as 1101 with reminder output, right ? But, its prints the true value 1011. Also, after the term
remainder = number%2, every-time due to recursion its again go in the top to use the function. How the `cout << remainder; ` able to print ?

The answer will help me a lot. Thanks :)
Last edited on
Wow, i just started to try and accomplish the same goal.
Slightly different method though... Im going to keep working on mine and get back to you, good luck!
Haha.. Cool. Very less reply today. Is this for weekend and people are still sleeping ?
Last edited on
why are you using recursion ??? can be done without ...
Recursion is important when you intend to use the same function repeatedly, such as in a game.

Coming back on topic, I can see an error.

 ``12`` ``````int main(void) /* this declaration is not good for what you try to achieve (from my knowladge) */``````

If I'm right you just told the c++ compilator that the main function will return void (=nothing).
Last edited on
Also, dont use this in function.

`cout << variable;`

`return variable;`
But if you will use `return variable;` you will need to declare the current function with a specific type, so not void. Declaring the function as void, you cannot return anything. So that is another error on your line 26. Let me give you an example:
 ``123456789101112`` ``````int binary(int number) { int remainder; if(number <= 1) { return number; } remainder = number%2; binary(number >> 1); return remainder; }``````