Recursive C ++ code

6

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 reproduce the operation using a recursive code but when I make the call passing 0 as a parameter it does not work, returning 1.

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

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

    
asked by anonymous 03.07.2016 / 05:30

2 answers

4

The two codes do not do the same thing. Where did the c variable go? In addition, it terminated earlier because the condition is reversed.

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

See working on ideone and on CodingGround .

I had to simulate what you're doing. In the next question, make a Minimum, Full and Verifiable example .

That said, avoid recursion in such cases . See When to use recursion and when to use loops? (attention that complicated does not mean large, in fact the simple is usually larger ). In that case he had to explain implementation details, which is not ideal. Recursion is the wrong mechanism for this problem.

    
03.07.2016 / 11:44
1

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

So your recursive function should look something like this:

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