#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    38
    Rep Power
    3

    Reverse string using recursion


    I am trying to reverse a string using recursion.

    Here is my code.

    Code:
    string reverse(string input, int index)
    {
    
    
        if (index == 0)
    		  {
    		    return "";
    		  }
    
    
        else
        {
            index--;
            cout << input.at(index);
            reverse(input, index);
        }
    }
    
    string reverse(string input)
    {
        reverse(input, input.size());
    
    }
    Here is the full code (including main, which tests my function)

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    string reverse(string input, int index)
    {
    
    
        if (index == 0)
    		  {
    		    return "";
    		  }
    
    
        else
        {
            index--;
            cout << input.at(index);
            reverse(input, index);
        }
    }
    
    string reverse(string input)
    {
        reverse(input, input.size());
    
    }
    
    
    int main()
    {
        cout << reverse("hello") << endl;
    	cout << reverse("world") << endl;
    	cout << reverse("test") << endl;
    	cout << reverse("THIS IS A LONGER SENTENCE!!!!!!!!!!") << endl;
    
    
    }
    What's happening is it prints out 'olleh' but then the program crashes. I'm thinking it's because my index is going out of bounds, but I'm not too sure.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,413
    Rep Power
    1871
    How about returning a result?
    Code:
    string reverse(string input)
    {
        return reverse(input, input.size());
    }
    Ditto in your other function as well, where you call the recursive function, but neglect to deal with the result.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    38
    Rep Power
    3
    Wow. I can't believe I missed that. Thank you.

    Originally Posted by salem
    How about returning a result?
    Code:
    string reverse(string input)
    {
        return reverse(input, input.size());
    }
    Ditto in your other function as well, where you call the recursive function, but neglect to deal with the result.

IMN logo majestic logo threadwatch logo seochat tools logo