Recursive code C++

Asked

Viewed 169 times

7

I have the following iterative function:

int getNumPastasColididas(int i){
    int c = 0;
    for(int i = 0; i < size; i++)
        c += table[i].hasColided;
    return c; // c = 89832
}

I tried to play the function using recursive code but when I make the call passing 0 as parameter it does not work, returning 1.

int getNumPastasColididas(int i){
    return (i < size) ?: table[i].hasColided + getNumPastasColididas(i + 1);
}

Why does recursive code not reproduce the iterative output? Where is the error?

  • 2

    Put the whole function to make it easy for us.

  • The answer helped you?

  • Did any of the answers below solve your problem? Do you think you can accept one of them? Check out the [tour] how to do this, if you still don’t know how to do it. This helps the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

2 answers

4

The two codes do not do the same thing. Where the variable went c? Moreover it closed before the time because the condition is reversed.

int getNumPastasColididas(int i, int c) {
    return (i < size) ? table[i].hasColided + getNumPastasColididas(i + 1, c) : c;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I had to simulate what you’re doing. Next question ask a Minimum, Complete and Verifiable Example.

That said, avoid recursion in such cases. Behold When to use recursion and when to use loops? (attention that complicated does not mean big, in fact the simple is usually bigger). In this case had to expose implementation detail, which is not ideal. Recursion is the wrong mechanism for this problem.

2

No variable is required c as our colleague suggested. The problem with your code is at the base of the recursion and in the condition of the ternary operator. When the condition i < size is true (left side of splitter :), recursion must continue. When the condition is false, the recursion must stop returning zero.

So your recursive function must be something like this:

int getNumPastasColididas(int i){
    return (i < size) ? table[i].hasColided + getNumPastasColididas(i + 1) : 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.