# C++ Reverse function that reverses the characters in a string given two indices using recursive

2476 views
6

This is the first time I am using this, as I usually find other people's questions on here but i can't seem to figure this one out. The problem states:

Using recursion, write a reverse function that reverses the characters in a string or character array given two indices (starting and ending). The string or the character array should reflect the reversal. Test by reading indices as input 11,18 (i.e. letters 12,19) and call the reverse function to reverse letters: 12-19

This is what I have so far:

``````string reverseFunction(string String, int indexStart, int indexEnd)
{
if(indexStart != 0)
{
for (int i = indexStart; i < indexEnd; i++)
{
swap(String[i], String[indexEnd - i - 1]);
}
}
else
{
for (int i = indexStart; i < indexEnd/2; i++)
{
swap(String[i], String[indexEnd - i - 1]);
}
}

return String;
}
``````

Any help is greatly appreciated. Thank you in advance!!

The steps for designing a recursive function are to determine how to reduce the problem, ie how to change the function arguments to reduce the scope of the function, and then to derive a base case for when the problem is solved. Check for your base case, and if it is not met, call your function again internally with arguments that reduce the problem. It won't do you any good to just get the answer given to you. Why don't you try and formulate a recursive strategy, and if/when it goes wrong, come here. Hint: 4! = 4*3*2 but it also equals 4*3!.

11

The problem is this block of code I guess:

``````if(indexStart != 0)
{
for (int i = indexStart; i < indexEnd; i++)
{
swap(String[i], String[indexEnd - i - 1]);
}
}
``````

You have your index wrong, and I don't understand why you have to split cases between indexStart=0 and indexStart!=0 since it'll be worked the same way. What you need is something like this:

``````for (int i = indexStart; i < (indexStart+indexEnd)/2; i++){
swap(String[i], String[indexEnd-i+indexStart]);
}
``````

(indexStart+indexEnd)/2 is the middle index of start index and end index, where you want to stop.

posted this