-2

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.

[output

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.

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 4
    Investigate the topic of *integer overflow*. You could do worse than look at SO Qs and As on the topic. – High Performance Mark Nov 04 '18 at 13:11
  • 5
    -858990820 = 0xCCCCD71C, and [MSVC fills uninitialized memory with 0xCCCCCCCC to help debugging](https://stackoverflow.com/q/370195/995714). Now you can see 0xCCCCD71C - 0xCCCCCCCC = 2640 which is 10 times the 264 in your previous result. Learn [how to debug small programs first](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – phuclv Nov 04 '18 at 13:15
  • I will look into it. Thanks. – Octavian Niculescu Nov 04 '18 at 13:19
  • Note that a[n] was never initialized. Also you should make sure that 'n` is less than 10. – drescherjm Nov 04 '18 at 13:26
  • 1
    It would have been helpful to your question if you had posted the `main()` as text instead of a picture of text. You could have also copied the output as text as well. It is possible to copy and paste from a cmd.exe window. – drescherjm Nov 04 '18 at 13:31

1 Answers1

0

You have a problem here:

    else
    {
        F(n - 1, a, k);
        if (a[n] % 2 == 0)
        {
            k = k * 10 + a[n];
        }
    }

If your initial call to this function is:

int a[10];
F(100, a, &k);

Then accessing a[n] is going to access a[10], which is beyond the allocated bounds of the array. Remember that in C, array indexes are 0 through n; in this case, 9 is the index of the last item.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351