I\'m having a very hard time understanding recursion. Can someone explain to me
ID: 3690228 • Letter: I
Question
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;
}
Explanation / Answer
Answer - I have explained the working of program in comments of program for better understanding of each statement.
#include <iostream>
using namespace std;
string reverseMe(string x)
{
if (x.length() == 1) { } //if string length is 1 means only one character string
else
{
cout<<endl<<x; //shows string as received by function
cout<<endl<<x.length(); //shows string length as received by function
x= reverseMe(x.substr(1,x.length()-1)) + x.at(0); //calling function in recursion while concatinating character at(0)
cout<<endl<<x; //shows string as reversed from top of stack in recursion
cout<<endl<<"second part " <<x.length(); //shows length of string as reversed from top of stack in recursion
}
return x;
}
int main()
{
string tmp;
cout<<" Enter a string: ";
getline(cin, tmp); //Input string to reverse
tmp = reverseMe(tmp); // funtion call
cout<<" REVERSE = [" << tmp << "]" << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.