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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;

void itob(short n,vector<int> binary);

int main()
{

    short n;
    vector <int> binary;
    cin>>n;
    itob(n, binary);
    for(int i = 0; i < binary.size(); i++)
    {
        cout<<binary.at(i)<<" ";
    }    

    return 0;
}
void itob(short n,vector<int> 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:

1
2
3
4
5
6
7
8
void itob(int n, std::vector<int> &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
i already solve this problem.
Thanks!

1
2
3
4
5
6
7
8
9
10
11
void itob(short n, vector<int> &bin)
{
    int d = n;

    if (n > 1)
    {
        d = n % 2;
        itob(n / 2, bin);
    }
    bin.push_back(d);
}
Congratulations! Happy programming! ;)
:D
Topic archived. No new replies allowed.