I need some explanation about the following piece of code:
It is used for converting decimal numbers to binary numbers code:
It is from a tutorial, but it puzzles me.
void binary(int);
void 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;
//cin.get();
}
}
void binary(int number) {
int remainder;
if(number <= 1) {
cout << number;
return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder;
//cin.get();
}
I used breakpoint to watch the data go through the program but at the end I can’t follow it.
What i see:
It takes a number and if the number <= to 1 it prints that number (0 or 1).
But before it does it first calculate the modulus of that number and put that in remainder.
Then it moves a bit to the right of number or does the same until number is smaller or equal to 1.
But then it keeps “cout remainder” for several times (depending how much 0/1 there are calculated)
But how is this possible ?
Is remainder a buffer? (i thought it keeps overwritten(because it is int), but it looks like there keeps being bits added and then printed several times)???
Can someone explain this slowly to me ?
The int is not overwritten because it [the int] is re-allocated as an automatic variable for each time you invoke the function
binary()recursively, so if you invoke itntimes recursively, you actually allocatendifferentints forremainder.So, it is “remembered” because they are different local variables. The allocation is usually made on the calls stack
How it works: let’s have a look at the stack of an example:
binary(5):now, you reinvoke
binary()withnumber = 5/2=2and again with
number = 2/2 = 1now, you reinvoke
binary()withnumber = 5/2=2, and get:Now, the stop condition is true, because
number <= 1-, so you printnumber[which is 1] and pop the first element from the call stack:and print 0, since it is the remainder at the top of the calls stack.
and do the same for the next “element” in the call stack:
and print the last remainder, 1.