#include <iostream>
usingnamespace 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 ?
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!
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: