0

I am trying to write a recursive method of reversing the string as below.

void reverse(string s,int i,int l)
{
    static int j;
    while(i<l)
    {
        char ch=s[i];
        cout<<ch<<endl;
        reverse(s,i+1,l);
        cout<<"after="<<ch<<endl;
        s[j]=ch;
        j++;
    }
    cout<<s<<endl;
    s[j]=0;
}

But my output is not correct. "after="<<ch is always printing last character of the string. Argument of the function is s is std::string, i is index starting from 0, and l is the length of the string. can any one point out where I am doing wrong thing.

8
  • 1
    What do you pass in for i and l and why is j static Commented Jul 24, 2013 at 4:47
  • 9
    And why do you have a "while" loop if you want a recursive algorithm?!? Commented Jul 24, 2013 at 4:48
  • One suggestion: you could modify your reverse function to return the reversed string and not do any printing at all. Commented Jul 24, 2013 at 4:50
  • 1
    Remove while with if and just include reverse in it . Commented Jul 24, 2013 at 4:51
  • 1
    You seem to be expecting ch to change after the recursive call. Why? Commented Jul 24, 2013 at 4:53

4 Answers 4

5

You already might have figured out the problem.

Another approach, if you don't like/want iterator or reverse function.

 string revStr(string str){
        if (str.length() <= 1) {
            return str;
        }else{
            return revStr(str.substr(1,str.length()-1)) + str.at(0);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Don't use a while() loop inside the function. Also, you need to pass the string by reference if you want it to be modified. Here's your code with a little improvement :):

void reverse(string& s,int i,int l)
{
    static int j = 0;
    if (i < l)
    {
        char ch=s[i];
        cout<<ch<<endl;
        reverse(s,i+1,l);
        cout<<"after="<<ch<<endl;
        s[j]=ch;
        j++;
    }
    cout<<s<<endl;
}

3 Comments

what do you mean by rev and j?
+1 Okay, I guess your code is most similar to his/her original code and fixed the bug..
Yeah, that was my intention. If you want to do it from scratch, Prashant Srivastava's solution is way better :)
1

There are several erros in your implementation like the other answers have already pointed out, the biggest one is that you are passing the string by value, so you are making changes on a copy of the original string and second the reason why the loop wont end is because you are using a while loop to break the recursion, but you are only incrementing "i" when you call reverse recursively, which mean that in the first calls to reverse "i" is not incremented, so the while will only break on the last call of the recursion, but then when it returns from it, it gets stuck in the previous call because "i" in that scope will never be greater than "l". that can be easily fix by changing the the while for an if instruction. Then your code will work as expected.

However, if you want to print your string backwards you should use the reverse iterators on the string class to traverse it in reverse order and then just print the characters as you go:

for (std::string::reverse_iterator rit = str.rbegin(); rit != str.rend(); ++rit)
    cout << *rit;

If you are using C++ and the string class, you should use its poweful features to your advantage.

If you are just doing an exercise on recursion, I dont quite understand what you are trying to accomplish exactly, but if I were to write a string backwards using recursion I would do something like this:

void reverse(string& s, int i = 0)
{
    // Break the recursion.
    if(i >= s.size())
        return;

    char ch = s[s.size() - (i + 1)];
    cout<< ch << endl;

    ++i;

    reverse(s, i);
}

4 Comments

why are you declaring i static
That way I dont have to pass "I" as parameter to the recursion function, whats wrong with it being static?
I don't think you understand the use of static, the next time your try to reverse a string the function will have the value of i from the last call
Oh, you are right, didnt think about it being call more than once.
0

I think you will have better luck with a recursive routine that has a signature like string reverse(const string s); and implementing the algorithm I described in my comment to the Q:

By utilizing the stack, and eliminating the i and l parameters, reversing the string s is the same as taking the first character and pre-pending the reverse of the substring of the last (s.length-1) characters, until you (recursively) get to a string that is 1 character in length, which is the string itself!

Comments

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.