My program should build a number (in the k
parameter) which is obtained with each of the even digits in the a[]
array. n
is the number of elements of the array.
void F (int n, int a[], int &k) {
if (n == 0)
{
if (a[0] % 2 == 0)
{
k = a[0];
}
else
{
k = -1;
}
}
else
{
F(n - 1, a, k);
if (a[n] % 2 == 0)
{
k = k * 10 + a[n];
}
}
}
BTW I'm not that good at recursion. It might not be an okay algorithm. I'm trying to get better.
The problem is as follows: if I cout k, it shows me -858990820.
If I use a cout k in the else condition to see what's happening, the result is fine UNTIL some point it suddenly turns into that negative number.
I think that number appears because of the array. It goes out of bounds at some point but I don't get when.
Calling F(n-1, a, k)
at the beginning of the else condition should have resolved this. (because the array stops at n-1 and if I call that in the else condition as the first thing in there it should not ever reach n).
Can you explain to me what's happening and help me fix it?
////edit: I forgot to mention: if there is no even number, k equals -1.