简体   繁体   中英

Recursive function understanding

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:

在此处输入图片说明

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.

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);

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)
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM