Positive Decimal to Binary

So I am trying to make a recursion function, to convert a positive decimal to binary but I seem to be having problems. For the output the binary isn't displayed. "Binary is: " is just empty or blank. If anyone can help and explain why my binary is not displaying I would appreciate it!

solved
Last edited on
At lines 22 & 23 there is a problem.

You are not writing "binary(number)" to the cout stream.

Possible fix bellow (haven't tested it:)

cout << number << " converted to binary is: " << binary(number) << endl;
Last edited on
Thanks I just did that, and a number now shows up! However, the number is just one digit for example if I enter 13 binary should show up as 1101 but only one digit shows up which is 1.
I think your binary() function should directly output the digit. Put the cout inside the function. You may need to re-arrange the logic slightly in order to get the digits output in the correct order. Make the return type void as the function won't return a particular value - though a return statement will probably still be useful or necessary for correct logic.

Or alternatively (a bit more complicated, in my opinion) have the function return a string, which would be built by concatenating '1' or '0' characters as appropriate.
Thanks everyone I took the recommendations and suggestions the program now displays the conversion. I just made changes to the function like so: (changed the data type to void)

1
2
3
4
5
6
7
8
void binary(int number) {
	if( number == 0 ) {
      return;
    }

   binary( number/2 );
   cout << number % 2;
}

Last edited on
Topic archived. No new replies allowed.