# Thread: Why does this recursive function not work otherwise.

1. ## Why does this recursive function not work otherwise.

This recursive functions works this way...

Code:
```void recurseReverse(vector<int>& aVec, intvec_sz start, intvec_sz end)
{
if ((end - start) <=1)
return;
else
{
int temp = aVec[end - 1];
aVec[end - 1] = aVec[start];
aVec[start] = temp;
recurseReverse(aVec, start + 1, end  - 1);
}
}```
but not this way...
Code:
```void recurseReverse(vector<int>& aVec, intvec_sz start, intvec_sz end)
{
while((end - start) > 1)
{
int temp = aVec[end - 1];
aVec[end - 1] = aVec[start];
aVec[start] = temp;
recurseReverse(aVec, start + 1, end  - 1);
}
}```
I assume that in the latter code, when it found that the end - start is one, it would return from the function

2. Code:
`while((end - start) > 1)`
end and start are not changed in the body of the loop. If the boody is entered it will never be left.
Kurt

3. I see. an if statement is more appropriate.

Edit:makes it work.

I have to look at the one I did in java, it was similar only with just arrays, not sure if i did a while loop or an if, but I see the stupid mistake I made.

4. Originally Posted by indigo0086
I see. an if statement is more appropriate.

Edit:makes it work.

I have to look at the one I did in java, it was similar only with just arrays, not sure if i did a while loop or an if, but I see the stupid mistake I made.
Isn't solution 1 an 2 the same now ?
Kurt

5. I changed the while to if
Code:
```void recurseReverse(vector<int>& aVec, intvec_sz start, intvec_sz end)
{
if((end - start) > 1)
{
....```

6. No, Kurt's point was that you just made the solution recursive again. If you want to make the solution iterative, that's fine, but you have to carefully consider the while condition.
Code:
```void iterReverse (vector<int>& aVec, intvec_sz start, intvec_sz end)
{
while((end - start) > 1) {
int temp = aVec[end - 1];
aVec[end - 1] = aVec[start];
aVec[start] = temp;
--end;
}
}```
or something like that.

7. I was aiming for recursive, I just oversaw that the while statement kind of made it go on forever.

And in your example you would have to add one to start, as I'm kind of shrinking the array on both sides by one, until it reaches the middle, if there is one.