Recursion

I'm having a very hard time understanding recursion. Can someone explain to me how this code works. I added some cout statements to try to understand whats going on but it only made me more confuse, I understand from abcdef to fe but after that I'm totally lost.


#include <iostream>

using namespace std;

string reverseMe(string x){

if (x.length() == 1) {

}

else{
cout << x<< endl;
cout <<x.length()<< endl;
x= reverseMe(x.substr(1,x.length()-1)) + x.at(0);
cout << x<< endl << endl;
cout <<"second part " <<x.length()<< endl << endl;
}
return x;
}



int main() {
string tmp;
cout << "Enter a string: ";
getline(cin, tmp);
tmp = reverseMe(tmp);
cout << "REVERSE = [" << tmp << "]" << endl;

}



Enter a string: abcdef
abcdef
6
bcdef
5
cdef
4
def
3
ef
2
fe

second part 2

fed

second part 3

fedc

second part 4

fedcb

second part 5

fedcba

second part 6

REVERSE = [fedcba]
Program ended with exit code: 0



Topic archived. No new replies allowed.