C++
Write a recursive function that reverses the given input string. No
loops allowed, only use recursive functions.
Do not add more or change the parameters to the original function.
Do not change the main program.
I had asked this before but the solution I was given did not
work.
#include
#include
using namespace std;
void reverse(string &str)
{
/*Code needed*/
}
int main()
{
string name = "sammy";
reverse(name);
cout << name << endl; //should display
"ymmas"
return 0;
}
#include <iostream> #include <string> using namespace std; void reverse(string &str) { if (str.size() > 1) { string sub = str.substr(1, str.size() - 2); reverse(sub); str.replace(1, str.size() - 2, sub); char temp = str[0]; str[0] = str[str.size() - 1]; str[str.size() - 1] = temp; } } int main() { string name = "sammy"; reverse(name); cout << name << endl; //should display "ymmas" return 0; }
Get Answers For Free
Most questions answered within 1 hours.