1

I've been doing a recursive function for exercise and there's a part which really confuses me. Here's what the entire code looks like:

void RekFunkcija(int * pok, int max)
{
    if (max != 0)
    {
        cout << pok[max - 1] << endl;
        RekFunkcija(pok + 1, max - 1);
    }
}

void main()
{
    const int max = 5;
    int niz[] = { max, 63, max, 126, 252 };
    RekFunkcija(niz, max);
}

So the output here is:

enter image description here

What's been confusing me is this part of the recursive function: cout << pok[max - 1] << endl; I don't understand why does it output always the last member of the array(252)? While the index number(max-1) is decrementing by 1? Shouldn't the output be: 252,126,5,63,5? Does it have anything to do with the pok+1 argument? Thank you in advance.

Kapobajza
  • 823
  • 6
  • 12

3 Answers3

5

The real problem is the use of pok+1 and max-1 together in the function. That is after the first iteration when 252 is printed, the situation is: pok on incrementing becomes [63,4,126,252] and max becomes 4. Now pok[max-1] again gives 4. So if you want all the array elements to be printed replace pok+1 in the function call RekFunkcija(pok + 1, max - 1); to RekFunkcija(pok, max - 1);

Crazy Psychild
  • 552
  • 5
  • 15
  • Thank you. I thought it had to do something with the `pok + 1` argument,but then again: I was really confused about it. But now it's clear to me. Thanks again. – Kapobajza Sep 06 '15 at 13:43
3

The recursive function shrinks the array (pointer increment on pok + 1) each turn and corrects the max argument. This is what happens in pseudo-ish code:

  1. RekFunkcija([5, 63, 5, 126, 252], 5)
  2. RekFunkcija([63, 5, 126, 252], 4)
  3. RekFunkcija([5, 126, 252], 3)
  4. RekFunkcija([126, 252], 2)
  5. RekFunkcija([252], 1)
1
RekFunkcija(pok + 1, max - 1);

you have got a problem in this recursive call. each call decreases max by 1 and that makes you print the max - (number of recursive calls) element, but you are also moving pok 1 element ahead, so you are printing the 5th element from the start, and then the 4th from the 2nd place, and so on.

Replace with: RekFunkcija(pok, max - 1);

Additionally, I would recommend using int main() instead of void main, as said here

Community
  • 1
  • 1
CIsForCookies
  • 10,156
  • 5
  • 36
  • 74