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.

1
  • 1
    replace pok+1 on pok. ideone.com/RjsQX3 Commented Sep 6, 2015 at 13:30

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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 Comment

So it shrinks it! I haven't realized this at all. You really cleared me up here,thank you very much.
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

1 Comment

Thank you for the answer and an additional thanks for the int main() suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.