Coding_master_guy's blog

By Coding_master_guy, 7 weeks ago, In English

i want to recursively reverse a string in c++ but this code only swaps first and last characters of the string and leave other characters as it is

#include <iostream>
#include<string>

using namespace std;

string reverse(string s, int start,int end)
{
    if(start < end)
    {
        swap(s[start] , s[end]);
        reverse(s , start +1 , end -1);
        
    }

     return s;
    
}

int main()
{
   string s;
   cin>>s;
   
   cout<<reverse(s,0,(s.length() -1));

    return 0;
}

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
7 weeks ago, # |
  Vote: I like it +14 Vote: I do not like it

reverse(s, start+1, end-1) -> return reverse(s, start+1, end-1)

»
7 weeks ago, # |
  Vote: I like it -7 Vote: I do not like it

"LoOoOooLoOoOoOoooOLooOoOoOoOooL. ROFL. LMAO. Google for AC solutions, generate random test cases and compare it against the output of your own program. You'll find the bug yourself."

~ The Old LanceTheDragonTrainer

»
7 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

try to make like this:

void reverse(string &s, int start,int end)
  • »
    »
    7 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    thanks i didnot think about pass by reference.

    But if we donot need to return character array or any type of array then why we need to return or pass by reference in case of "string" ?

    • »
      »
      »
      7 weeks ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Because all arrays are automatically passed by reference by default.

    • »
      »
      »
      7 weeks ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Using a call-by-value to an object parameter whose data size is large in recursive function declaration is not recommended in C++. The reason is that the C++ compiler creates a new copy of the called parameter object, and then pushes the starting address of this new object to the calling parameters stack. In your call-by-value reverse function, this means that the program requires $$$O(N^2)$$$ dynamic memory to reverse an $$$N$$$-character string. Check the execution time and memory requirements of call-by-value and call-by-reference of your updated program.

      Call-by-value

      Call-by-reference