### Integer to binary(Using recursivity)

I'm trying to develop a recursive function to convert an integer number into binary and putting the result into a vector using the following logic:
Every function call, divide the number by 2, if the remainder is equal to 0, insert a 0 in vector, if not, put one in the vector.

Soon after when the function ends, I show the contents of the vector.
However, nothing is displayed on the screen.
Why?

 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````#include #include #include #include using namespace std; void itob(short n,vector binary); int main() { short n; vector binary; cin>>n; itob(n, binary); for(int i = 0; i < binary.size(); i++) { cout< binary) { if(n > 0 ) { if(n % 2 == 0) { binary.push_back(1); } else { binary.push_back(0); } itob(n-1,binary); } } ``````
closed account (D80DSL3A)
You're passing the vector by value so its contents can't be modified by the function. The function is working with a copy.
Pass the vector by reference instead:
`void itob(short n,vector<int>& binary);// note the & `
Thank you.
Why when I pass the vector as parameter, it does not automatically pass by reference? Like an array?
Why is not the same thing?
Arrays don't follow the same rules as everything else in C++ - don't base any assumptions on how arrays behave ;)

Arrays are generally passed by pointer, not by reference, without you knowing it. You can force them to be passed by reference, though.
Would it make any difference?
Passing an array by pointer or reference?
@romulosd

I'm afraid that the recursive function is wrong:

1. the vector must store the remainders modulo 2, (n % 2 without if test)
2. recursive process must be resumed with n / 2 not with n - 1

and so the function will be as follows:

 ``12345678`` ``````void itob(int n, std::vector &binary) { if(n > 0) { binary.push_back( n % 2); itob(n / 2, binary); } }``````

and lines 16 - 19 (your code) must read the vector from the end to the beginning.
Yes @condor
 ``1234567891011`` ``````void itob(short n, vector &bin) { int d = n; if (n > 1) { d = n % 2; itob(n / 2, bin); } bin.push_back(d); }``````