0

This code converts decimal integer into binary. This is working perfectly. I know this has been done using recursion method...but I am not understanding how the parameter is working on the line 8 of this function. thanks in advance :) .

void binary(int number) {
int remainder;
if(number <= 1) {
    cout << number;
    return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder;

}

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Rabi
  • 9
  • 3

1 Answers1

1

In most "C inspired languages*", the operator >> represents the right (bitwise) shift operator. So the code

binary(number >> 1); 

passes a value to the recursive call to binary(), which is shifted by one bit to the right (i.e. the same as integer division by 2).

The recursion stops when the number is <= 1, i.e. there are no more powers of 2 to divide the remaining number through by.

In the interim, the modulo 2 (% 2) remainder for the call is held over and written after the inner recursive call, so that it will retain the correct position in the power of 2.

e.g.

12 Decimal
 / 2 = 6 remainder 0   // printed fourth
 / 2 = 3 remainder 0   // printed third
 / 2 = 1 remainder 1   // printed second
 > <= 1 so Print 1     // printed first

So 1100 will be printed.

* Wikipedias terminology

StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 1
    I see no advantage of adding an answer since yours is preciously enough but it can be more informative to the OP if you can add the shift operators' structure like "operand to manipulate", "shift operator", "operand to use as shift count that as in bit count". This way he can see that he can mix the shift operands whatever way he wants, i think. – Hasan Manzak Dec 22 '14 at 17:12